fbmessenger

6.0.0 · maintenance · verified Thu Apr 16

fbmessenger is a Python library designed to simplify communication with the Facebook Messenger API. It provides a structured way to handle webhooks, send various message types (text, attachments, templates), and manage Facebook Page interactions. The current version is 6.0.0, with the last significant update in April 2019. While not actively developed with new features, it provides core functionality for Messenger bot development.

Common errors

Warnings

Install

Imports

Quickstart

This Flask example demonstrates how to set up a basic webhook for the Facebook Messenger API using fbmessenger. It listens for incoming messages, verifies the webhook, and echoes back received text messages. Ensure you have Flask installed (`pip install Flask`) and configured environment variables for `FB_PAGE_TOKEN`, `FB_VERIFY_TOKEN`, and optionally `FB_APP_SECRET` based on your Facebook App setup.

import os
from flask import Flask, request
from fbmessenger import BaseMessenger, MessengerClient

app = Flask(__name__)
app.debug = True

# Extend BaseMessenger and implement webhook handlers
class Messenger(BaseMessenger):
    def __init__(self, page_access_token, app_secret=None):
        self.page_access_token = page_access_token
        self.app_secret = app_secret
        self.client = MessengerClient(self.page_access_token, app_secret=self.app_secret)

    def message(self, message):
        # Handle incoming text messages
        if 'text' in message['message']:
            received_text = message['message']['text']
            sender_id = message['sender']['id']
            self.client.send({'text': f'Received: {received_text}'}, 'RESPONSE', recipient_id=sender_id)

    def delivery(self, message):
        pass # Handle message delivery confirmations

    def read(self, message):
        pass # Handle message read confirmations

    def account_linking(self, message):
        pass # Handle account linking events

    def postback(self, message):
        pass # Handle postback events

    def optin(self, message):
        pass # Handle opt-in events

# Initialize Messenger with tokens from environment variables
messenger = Messenger(
    os.environ.get('FB_PAGE_TOKEN', ''),
    app_secret=os.environ.get('FB_APP_SECRET', '')
)

@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
    if request.method == 'GET':
        # Webhook verification
        if request.args.get('hub.verify_token') == os.environ.get('FB_VERIFY_TOKEN'):
            return request.args.get('hub.challenge')
        raise ValueError('FB_VERIFY_TOKEN does not match.')
    elif request.method == 'POST':
        # Handle incoming messages
        messenger.handle(request.get_json(force=True))
        return ''

if __name__ == '__main__':
    # Remember to set FB_PAGE_TOKEN, FB_VERIFY_TOKEN, and FB_APP_SECRET (optional) environment variables.
    # Example: export FB_PAGE_TOKEN='your_page_access_token'
    #          export FB_VERIFY_TOKEN='your_verify_token_string'
    #          export FB_APP_SECRET='your_app_secret' (if enabled)
    app.run(host='0.0.0.0', port=5000)

view raw JSON →