项目作者: RHDZMOTA

项目描述 :
Scala chatbot utils for fb-messenger platform.
高级语言: Scala
项目地址: git://github.com/RHDZMOTA/fb-messenger.git
创建时间: 2018-05-11T15:50:45Z
项目社区:https://github.com/RHDZMOTA/fb-messenger

开源协议:Apache License 2.0

下载


FB-Messenger Scala Models

Serializable scala models for the Webhook and Send API of the Facebook Messenger Platform.
This repo follows the SemVer Specification.

  • Current version: 1.0.0

Usage

The original objective was to provide the models for the webhook and send APIs to facilitate the development
of chatbots in the facebook messenger platform.

A chatbot project written in Scala might look something like this:

  • A server validated by facebook to receive webhook events (e.g. Akka HTTP).
  • Usage of io.circe.decode and the webhook models to interpret the webhook events.
  • Pattern matching to identify message types (text, attachments, fallback, etc).
  • Process the messages (e.g. ML, expert model, business logic).
  • Build the response using the Send models.
  • Send the response using io.circe.syntax for json encoding and a client http to send the post request.

A more advanced implementation involves streaming technologies, natural language processing, reinforced learning
and complex business logic.

Webhook API

The webhook API is needed when a message is send to a facebook page.
You may receive text messages, attachments or fallback.
For a precise definition of these elements see the messenger platform official documentation for webhook events.

Usage example:

  1. import io.circe.parser.decode
  2. import com.rhdzmota.fbmessenger.webhook.model.Event
  3. import com.rhdzmota.fbmessenger.webhook.model.implicits.Decoders._
  4. // This is a facebook callback (payload a post request from fb representing an event)
  5. val eventJsonString: String = ???
  6. // We can use our implicit decoders with circe to get the event object.
  7. val result = decode[Event](eventJsonString)
  8. result match {
  9. case Left(error) => println("There was an error decoding the eventJsonString: " + error.toString)
  10. case Right(event) => println("We have an event.")
  11. }

Event json example:

  1. {
  2. "object":"page",
  3. "entry":[
  4. {
  5. "id":"<PAGE_ID>",
  6. "time":0,
  7. "messaging":[
  8. {
  9. "sender":{
  10. "id":"<PSID>"
  11. },
  12. "recipient":{
  13. "id":"<PAGE_ID>"
  14. },
  15. "timestamp":0,
  16. "message":{
  17. "mid":"<MID>",
  18. "seq":0,
  19. "attachments":[
  20. {
  21. "title":"<TITLE>",
  22. "url":"<URL>",
  23. "type":"location",
  24. "payload":{
  25. "coordinates":{
  26. "lat":0,
  27. "long":0
  28. }
  29. }
  30. }
  31. ]
  32. }
  33. }
  34. ]
  35. }
  36. ]
  37. }

Send API

The send API is needed in order to send a message from a facebook page to a user. For a complete decription of the API see the messenger platform official documentation to send requests.

Usage example:

  1. import io.circe.syntax._
  2. import com.rhdzmota.fbmessenger.send.model.reply._
  3. import com.rhdzmota.fbmessenger.send.model.message._
  4. import com.rhdzmota.fbmessenger.send.model.message.quickreply._
  5. import com.rhdzmota.fbmessenger.send.model.implicits.Encoders._
  6. val recipient = Recipient("<PSID>") // Message recipient (user)
  7. val quickReply = Text("text", "<TITLE>", "<PAYLOAD>", None) // Quick reply buttons (create none or many)
  8. val withText = WithText("<TEXT-1>", Some(List(quickReply))) // Create text message with quick reply list (a message can be withText or withAttachment)
  9. val withMessage = Reply.withDefaultConfigMessage(recipient, withText) // Define reply element (a reply can be done with a message or with an action)
  10. // You can use the implicit encoders and circe syntax to serialize to json
  11. withMessage.asJson

Send request message example:

  1. {
  2. "messaging_type": "RESPONSE",
  3. "recipient": {
  4. "id": "<PSID>"
  5. },
  6. "message": {
  7. "text": "<TEXT-1>",
  8. "quick_replies": [
  9. {
  10. "content_type": "text",
  11. "title": "<TITLE>",
  12. "payload": "<PAYLOAD>"
  13. }
  14. ]
  15. },
  16. "notification_type": "REGULAR"
  17. }

Post request to fb-messenger

This repository only contains the models to interact with the facebook messenger API. If you are using the Send API models, you will need to figure out a way of sending the
request to fb messenger. In this section we present a suggestion for sending the requests using akka http async client library.

Dependencies

  • Akka HTTP

Create the required implicit variables for the Actor Model.

  1. import akka.actor.ActorSystem
  2. import akka.stream.{ActorMaterializer, Materializer}
  3. import scala.concurrent.ExecutionContext
  4. trait Context {
  5. implicit val actorSystem: ActorSystem = ActorSystem()
  6. implicit val executionContext = actorSystem.dispatcher
  7. implicit val materializer: Materializer = ActorMaterializer()
  8. }

Create a Client Http object or trait with the post method.

  1. object ClientHttp extends Context{
  2. def postRequest(targetUrl: String)(data: String): Future[HttpResponse] =
  3. Http(actorSystem).singleRequest(
  4. HttpRequest(
  5. HttpMethods.POST,
  6. targetUrl,
  7. entity = HttpEntity(ContentTypes.`application/json`, data)
  8. ))
  9. }

Now we can send a request to the Facebook Messenger.

  1. def send(data: String, apiKey: String): Unit =
  2. ClientHttp.postRequest(Settings.Facebook.sendUri + apiKey)(data).onComplete {
  3. case Failure(e) => println(s"- Failed to post:\n$data\n- Reason:\n$e")
  4. case Success(response) => println(s"- Server responded with:\n$response")
  5. }

Contributions and authors

Feel free to create a PR or raise an issue. For more information, contact the developers of this repo:

License

To be defined.