fbmessenger
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
-
ValueError: FB_VERIFY_TOKEN does not match.
cause The `hub.verify_token` sent by Facebook during webhook setup does not match the `FB_VERIFY_TOKEN` configured in your application's environment or code.fixDouble-check that the `FB_VERIFY_TOKEN` environment variable in your application exactly matches the 'Verify Token' string you entered in your Facebook App's Messenger Platform settings. Pay attention to case sensitivity and leading/trailing spaces. -
API calls failing with connection errors (e.g., requests.exceptions.ConnectionError, timeout errors).
cause The application cannot establish a stable network connection to Facebook's API endpoints, or the API request timed out. This can be due to local network issues, firewalls, or temporary Facebook server problems.fixVerify your server's internet connectivity and firewall rules. Implement retry logic with exponential backoff for API calls. Check Facebook's developer status page for any ongoing API issues. Consider increasing the `timeout` parameter for `MessengerClient` methods if connections are slow. -
Messages are sent but not received by users, or messages fail with unexpected errors related to permissions or recipient_id.
cause This often indicates issues with the Page Access Token (expired, incorrect), insufficient permissions granted to your Facebook App, or using an invalid `recipient_id` (e.g., not a Page-Scoped ID, or a user who has not interacted with the page).fixRegenerate your Page Access Token in the Facebook Developer Portal. Ensure your Facebook App has all necessary permissions (e.g., `pages_messaging`). Confirm that `recipient_id` values are valid Page-Scoped IDs obtained from incoming webhook events.
Warnings
- breaking Version 6.0.0 introduced a breaking change by switching the input parameter from 'message' to 'recipient_id' for methods like send().
- gotcha Facebook Page-Scoped IDs (PSIDs) must be used when interacting with the Messenger API. These are unique to your page and differ from global Facebook user IDs or app-scoped IDs from other integrations. Using incorrect IDs will result in failed API calls.
- gotcha The Facebook Messenger API frequently updates, sometimes introducing changes to message types, permissions, or security features (e.g., end-to-end encryption by default). While fbmessenger aims to abstract this, underlying API changes can affect compatibility or require updates to your bot's logic.
Install
-
pip install fbmessenger
Imports
- BaseMessenger
from fbmessenger import BaseMessenger
- MessengerClient
from fbmessenger import MessengerClient
from fbmessenger.client import MessengerClient
Quickstart
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)