Skip to main content

Facebook messenger bot framework

Project description

Introduction

koslab.messengerbot makes writing Facebook Messenger Bot easier by providing a framework that handles and abstract the Bots API. It is originally developed using Morepath as the web request processor and the default hub implementation is on morepath, but this library should work with any Python web frameworks

Example: Writing An Echo Bot

Lets install koslab.messengerbot

pip install koslab.messengerbot

Now lets write our EchoBot in echobot.py

from koslab.messengerbot.bot import BaseMessengerBot

# bot implementation
class EchoBot(BaseMessengerBot):

   GREETING_TEXT = 'Hello!. EchoBot, at your service!'
   STARTUP_MESSAGE = {'text': 'Hi!, lets get started!' }

   def message_hook(self, event):
       text = event['message'].get('text', '')
       self.send(recipient=event['sender'], message={'text': text})

And now lets write a hub config file, config.yml.

webhook: webhook
use_message_queue: false
message_queue: amqp://guest:guest@localhost:5672//
hub_verify_token: <MY-VERIFY-TOKEN>
bots:
  - page_id: <PAGE-ID>
    title: EchoBot
    class: echobot:EchoBot
    access_token: <PAGE-ACCESS-TOKEN>

Start the bot

messengerbot_hub config.yml

Finally proceed to follow the Messenger Platform Getting Started guide to get your bot configured and registered in Facebook.

Bot Configuration

POSTBACK_HANDLERS

Dictionary mapping of payload to name of object method that will handle the payload. Default value is:

POSTBACK_HANDLERS = {}

Example:

POSTBACK_HANDLERS = {
   'mypostback': 'mypostback_hook'
}

def mypostback_hook(self, event):
    ...
GREETING_TEXT

Greeting text for new threads. Default value is:

GREETING_TEXT = 'Hello World!'
STARTUP_MESSAGE

Message object to be sent when Get Started menu is clicked. Default value is:

STARTUP_MESSAGE = { 'text' : 'Hello World!' }
PERSISTENT_MENU

Persistent menu call_for_action buttons configuration. Default value is:

PERSISTENT_MENU = [{
   'type': 'postback',
   'title': 'Get Started',
   'payload': 'messengerbot.get_started'
}]

Bot Hooks

Following are the list of hooks that can be implemented on the bot

message_hook

Handles Message Received and Message Echo event.

postback_hook

Handles Postback Received event. This hook have a default implementation which triggers methods based on payload value. To define the mapping, configure POSTBACK_HANDLERS class variable.

authentication_hook

Handles Authentication event.

account_linking_hook

Handles Account Linking event.

message_delivered_hook

Handles Message Delivered event.

message_read_hook

Handles Message Read event

Send API

BaseMessengerBot class provide a send method to send responses to Facebook Messenger Bot service. Parameters are:

recipient

Recipient object. Eg: { 'id': '12345678'}

message

Message object. Refer to Facebook Send API reference for supported messages

sender_action

Sender actions. Supported values: mark_seen, typing_on, typing_off

Note: If message is defined, sender_action value will be ignored.

A convenience method reply can also be used to send a response. Parameters are:

event

Event object

message

Accepts string, callable or message object. Strings are automatically converted into message object. Callable will be called with the event object as its parameter.

Postback Payload

Postback values may be a JSON object or a string. In the case of Postback in JSON object format, an event key is required for routing postbacks to the right handler by postback_hook. For string postback values, the whole string is treated as the event key.

Session

Session Management is provided through a thin wrapper around Beaker Cache. Current conversation session variable may be acquired through get_session method on BaseMessengerBot class. Session object is dict-like and may be treated as such.

def message_hook(self, event):
    session = self.get_session(event)

Messenger Bot with AMQP

AMQP queuing is supported by the hub process. To use this, in config.yml simply set use_message_queue to true and configure the transport uri to the message queue on message_queue setting. The queue is implemented using Kombu, so you may also use other transports that are supported by Kombu

use_message_queue: true
message_queue: amqp://guest:guest@localhost:5672//

Conversation API

NOTE: This is a draft spec. Not yet implemented. Inputs are welcomed.

Spec

conversation: myconversation
steps:
   - message: What is your name?
     type: text
     store: name
   - message: Please share your photo
     type: image-attachment
     store: photo
   - message: Please share your location
     type: location-attachment
     store: location
   - message:
       - type: generic-template
         elements:
            - title: Summary
              subtitle: Summary
              image_url: ${data['photo']['url']}
              buttons:
                  - type: postback
                    title: Save
                    payload: myconversation.save

Contributors

Note: place names and roles of the people who contribute to this package

in this file, one to a line, like so:

  • Mohd Izhar Firdaus Bin Ismail, Original Author

Changelog

1.0b5 (2016-08-09)

  • Rearrange priority of event handlers so that quick reply postbacks are caught [Izhar Firdaus]

1.0b4 (2016-08-08)

  • Ignore CLI when starting up hub [Izhar Firdaus]

1.0b3 (2016-08-08)

  • Ensure that all child processes are killed when parent is terminated. [Izhar Firdaus]

1.0b2 (2016-07-13)

  • Bug with page_id mapping. Ensure it is read as string now instead of integer [Izhar Firdaus]

1.0b1 (2016-07-13)

  • Initial fully functional bot framework with hub implementation [Izhar Firdaus]

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

koslab.messengerbot-1.0b5.tar.gz (11.3 kB view details)

Uploaded Source

File details

Details for the file koslab.messengerbot-1.0b5.tar.gz.

File metadata

File hashes

Hashes for koslab.messengerbot-1.0b5.tar.gz
Algorithm Hash digest
SHA256 f17ff64d959a8d9273c706d3af96fa204fd14a3a9e6eca5f7e85c6094c1a4548
MD5 790ecb1a2f6aebeba42bc00f1a1a98c7
BLAKE2b-256 3b4d8b441b72ac39eb3f7657337b088f9429a149b154c5121515590ab3cfcaed

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page