项目作者: riyaz-ali

项目描述 :
A JavaScript API for creating Facebook Messenger bots in node
高级语言: JavaScript
项目地址: git://github.com/riyaz-ali/sprinejs.git
创建时间: 2017-08-07T05:51:10Z
项目社区:https://github.com/riyaz-ali/sprinejs

开源协议:MIT License

下载


Sprine

A Node.js client for the Facebook Messenger Platform. The API is largely influenced by messenger-bot.

Installation

  1. npm install git+https://github.com/riyaz-ali/sprinejs.git

Example

  1. // express (or any connect-compatible app)
  2. const app = require("express")()
  3. const bodyParser = require("body-parser")
  4. // sprine bot
  5. const Bot = require("sprine").Bot
  6. const send = require("sprine").send //- module for Sender API
  7. let bot = new Bot({
  8. token: "PAGE_TOKEN",
  9. verify: "VERIFICATION_TOKEN"
  10. })
  11. /** subscribe to bot events */
  12. //- error
  13. bot.on("error", err => console.error(err))
  14. //- message
  15. bot.on("message", (event, reply) => {
  16. // event is an instance of FacebookEvent
  17. console.log("[%s]: %s", event.sender, event.timestamp)
  18. // send an image attachment
  19. let msg0 = new send.Message(
  20. new send.ImageAttachment("http://example.com/welcome.png")
  21. )
  22. // send quick reply template
  23. let msg1 = new send.Message(
  24. "Red or Blue?",
  25. [send.QuickReply.text("Red", "COLOR_RED"),
  26. send.QuickReply.text("Blue", "COLOR_BLUE")]
  27. )
  28. // ask for location
  29. let msg2 = new send.Message(
  30. "Weather! but for where?",
  31. send.QuickReply.location()
  32. )
  33. //- Reply to the message
  34. // 1. Simple text
  35. reply("Hello there! I got your message")
  36. // 2. Composed Message
  37. reply(msg1) // or msg2, msg3, etc.
  38. // 3. Or a complete Payload
  39. let payload = new send.Payload(
  40. new send.Recipient(event.sender),
  41. msg2,
  42. null, // sender actions
  43. send.Notification.SILENT // notification type
  44. )
  45. reply(payload).then(resp => console.log(resp)
  46. })
  47. // use a middleware to parse post data. This is required from the application side.
  48. app.use(bodyParser.json())
  49. // add a middleare to your app to handle Messenger webhook calls
  50. app.use("/facebook", bot.middleware())
  51. // run
  52. app.listen(8080)

Note: The application must provide a connect-compatible middleware to parse POST data or else the bot will raise an exception about missing data argument when a message is received.

Reference

  1. class Bot extends EventEmitter

The base class the user mainly interacts with. This class provides functions and events
that helps the user tap into events and messages received from Facebook and respond to them.

let bot = new Bot(options)

Returns a new Bot instance

options - Object

  • token {string} - Your Page Access Token. Required.
  • verify {string} - Verification token for one-time setup. Required, if you want the bot to handle verification for you.
  • subscribe {boolean} - Subscribe App to the Page on initialization. Optional.

Bot#middleware()

Returns a connect-compatible middleware function.

Bot#sendMessage(to, data [, callback])

Send a message data to target to. Returns a promise.
Also see Facebook Send API

  • to {string} - Page-scoped ID of the intended recipient. Required, if data is not an instance of Payload. If data is an instance of Payload then this is ignored.
  • data {string|Message|Payload} - The message to send. Can be a string/text, a Message or a Payload. Required.

Bot#handleMessage(data)

The message processing routine. Either invoke this routine with the data received from Facebook or use the middleware
which invokes it internally. This routine parses the message and trigger events for each kind of message received.

  • data {object} - Data received from Facebook. Required.

Bot#handleVerification(request, response)

Handle webhook validation request.

  • request - A connect-compatible request object.
  • response - A connect-compatible response object.

Bot#subscribe()

Subscribes the App to Page programmatically. Returns a promise.

Bot#getProfile(id [, callback])

Get the User’s Profile. Returns a promise which resolves either to a User Profile object or an empty object depending on whether the profile is available or not.

  • id {string} - Page-scoped ID of the user. Required. Usually, this is the event.sender property of the concerned message.

Bot#setField(field, payload [, callback])

Sets a field for the Messenger Profile API

  • field {string} - Name of the field. Required.
  • payload {object} - Object payload to set. Required.

Bot#deleteField(field [, callback])

Deletes a field for the Messenger Profile API

  • field {string}: Name of the field to delete

Bot#setGetStartedButton([callback])

Shorthand function to enable the Get Started Button

Bot#removeGetStartedButton([callback])

Shorthand function to disable the Get Started Button

Events

Every event, except the error event, receives a FacebookEvent object and a reply(data [, callback]) function that’s an alias to Bot#sendMessage(to, data [, callback]) with a bound ID.

List of events:

  1. message: fired when a message is received.
  2. echo: fired when an echo is received.
  3. postback: fired when a postback is received.
  4. delivery: fired when a delivery receipt is received.
  5. read: Fired when a read receipt is received.
  6. authentication: Fired when an optin is received.
  7. referral: Fired when a referral is received.
  8. account-linked: Fired when an Account Linking event with status linked is received.
  9. account-unlinked: Fired when an Account Linking event with status unlinked is received.
  10. unknown: Fired when an unknown event is received.
  1. class FacebookEvent

The FacebookEvent class. The instance of this class is passed to the event listeners when an event is received.

FacebookEvent#sender

A getter-property to access the event’s sender id.

FacebookEvent#timestamp

A getter-property to access the event’s timestamp.

FacebookEvent#type

A getter-property to get the event’s type.

FacebookEvent#data

A getter-property to get the data object associated with the event. The shape of this object depends on the type of event, see Webhook Reference for more details.

Send API

For a reference to Send API, check the documentation here

Todo

  • Add classes to wrap message data recieved from Facebook and provide easy interface to work with that
  • Add custom callback for specific types of Postback payloads. For eg., we can have a QuickReply with a payload field set to SOME_PAYLOAD, then we can listen for that specific Postback by having something like, bot.on('postback:SOME_PAYLOAD', (event, reply) => {...})
  • Add tests
  • (Low Priority) Add some generic session/context management support within the bot itself. The argument for this is that some of us would be using this library alongwith other AI-services (like api.ai) for which we may want to add some kinda session support to our bot

PR for adding above mentioned features are welcomed! For other feature request or for reporting bugs use Github Issues.