/python-messengerbot-sdk

Python Messenger SDK

Primary LanguagePythonApache License 2.0Apache-2.0

python-messengerbot-sdk

SDK of the Facebook Messenger API for Python.

Most code structure were followed by line-bot-sdk-python

Install

$ pip install python-messengerbot-sdk

Synopsis

Usage:

from flask import Flask, request

from facebookbot import (
    FacebookBotApi, WebhookHandler
)

from facebookbot.models import (

    TextMessageEvent, TextSendMessage, TextSendMessage
)

app = Flask(__name__)

facebook_bot_api = FacebookBotApi("YOUR_PAGE_ACCESS_TOKEN")

handler = WebhookHandler()


@app.route('/callback', methods=['GET'])
def verify():
    # when the endpoint is registered as a webhook, it must echo back
    # the 'hub.challenge' value it receives in the query arguments
    if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
        if not request.args.get("hub.verify_token") == "YOUR_VERIFY_TOKEN":
            return "Verification token mismatch", 403
        return request.args["hub.challenge"], 200

    return "Hello world", 200


@app.route('/callback', methods=['POST'])
def webhook():

    # endpoint for processing incoming messaging events

    body = request.get_json()

    handler.handle(body)

    return "ok", 200

@handler.add(TextMessageEvent)
def handle_text_message(event):
    facebook_bot_api.push_message(
       event.sender.id,
       message=TextSendMessage(text=event.message.text)
    )

if __name__ == "__main__":
    app.run()

API

MessengerBotApi

__init__(self, page_access_token, endpoint='https://graph.facebook.com', timeout=5, http_client=RequestsHttpClient)

Create a new FacebookBotApi instance.

facebook_bot_api = facebookbot.LineBotApi('YOUR_PAGE_ACCESS_TOKEN')

You can override the timeout value for each method.

push_message(self, user_id, message, is_sender_action = True, timeout = None)

Send messages to users

facebook_bot_api.push_message(user_id, TextSendMessage(text='Hello World!'))

broadcast(self, message, notification_type="REGULAR", timeout = 60)

broadcast to all page followers but limited to 10,000 per message.

facebook_bot_api.broadcast(TextSendMessage(text='Hello World!'))

get_profile(self, user_id, timeout=None)

Get user profile information.

profile = facebook_bot_api.get_profile(user_id)

print(profile.first_name)
print(profile.last_name)
print(profile.gender)
print(profile.profile_pic)
print(profile.locale)
print(profile.timezone)

setup_started_button(self, timeout=None)

setup started button, when press it, then responding from GetStartedEvent

facebook_bot_api.setup_started_button()

setup_persistent_menu(self, persistent_menus, timeout=None)

setup persistent menu

persistent_menus=[
    PersistentMenu(
        call_to_actions=[
            NestedAction(
                title="nested_title",
                call_to_actions=[
                    PostbackAction(title="nested_postback", payload="nested_postback"),
                    URLAction(title="nested_url", url='https://example.com/')
                ]
            ),
            PostbackAction(title="postback", payload="action=buy&itemid=1"),
            URLAction(title="url", url='https://example.com/')
        ]
    )
]

facebook_bot_api.setup_persistent_menu(persistent_menus)

upload_remote_attachment(self, attachment_send_message, timeout=None)

upload remote attachment(e.q. FacebookURL or https url) to reuse and get attachment_id

image = ImageSendMessage(image_url="pic_url.jpg")
attachment_id = facebook_bot_api.upload_remote_attachment(image)
print(attachment_id)

upload_local_attachment(self, attachment_send_message, timeout=None)

upload local attachment to reuse and get attachment_id

attachment_id = facebook_bot_api.upload_local_attachment(
    file_path = "/your/file/path"
    file_type = "image/jpeg" or "image/png" or "video/mpeg"
)
print(attachment_id)

Message objects

The following classes are found in the facebookbot.models package.

TextSendMessage

text_message = TextSendMessage(text='Hello, world')

ImageSendMessage

image_message = ImageSendMessage(
    image_url='https://example.com/original.jpg',
    is_reusable=True
)

VideoSendMessage

video_message = VideoSendMessage(
    video_url='https://example.com/original.mp4',
    is_reusable=True
)

AudioSendMessage

audio_message = AudioSendMessage(
    audio_url='https://example.com/original.m4a',
    is_reusable=True
)

FileSendMessage

file_message = FileSendMessage(
    file_url='https://example.com/original.pdf',
    is_reusable=True
)

TemplateSendMessage - ButtonsTemplate

buttons_template_message = TemplateSendMessage(
    template=ButtonsTemplate(
        text="Buttons template",
        buttons=[
            PostbackAction(
                title="postback",
                payload="action=buy&itemid=1"
            ),
            URLAction(
                title="url",
                url="http://example.com/",
                webview_height_ratio='full',
                messenger_extensions=None,
                fallback_url=None
            )
        ]
    )
)

TemplateSendMessage - GenericTemplate

generic_template_message = TemplateSendMessage(
    template=GenericTemplate(
        elements=[
            GenericElement(
                title="GenericElement 1",
                image_url="https://example.com/item1.jpg",
                subtitle="description1",
                default_action=URLAction(url="http://example.com/"),
                buttons=[
                    PostbackAction(title="postback_1", payload="data_1"),
                    URLAction(
                        title="url_1",
                        url="http://example.com/1",
                        webview_height_ratio='full',
                        messenger_extensions=None,
                        fallback_url=None
                    )
                ]
            ),
            GenericElement(
                title="GenericElement 2",
                image_url="https://example.com/item2.jpg",
                subtitle="description2",
                default_action=URLAction(url="http://example.com/"),
                buttons=[
                    PostbackAction(title="postback_2", payload="data_2"),
                    URLAction(
                        title="url_2",
                        url="http://example.com/2",
                        webview_height_ratio='compact',
                        messenger_extensions=None,
                        fallback_url=None
                    )
                ]
            )
        ]
    )
)

TemplateSendMessage - MediaTemplate

By attachment_id

image_send_message = ImageSendMessage(url="https://via.placeholder.com/1024x1024")

attachment_id = fb_bot_api.upload_attachment(image_send_message)

media_template_message = TemplateSendMessage(
    template=MediaTemplate(
        elements=[
            ImageElement(
                attachment_id=attachment_id,
                buttons=[
                    PostbackAction(title="postback_1", payload="data_1"),
                    URLAction(
                        title="url_1",
                        url="http://example.com/1",
                        webview_height_ratio='full',
                        messenger_extensions=None,
                        fallback_url=None
                    )
                ]
            )
        ]
    )
)

By facebook_url

media_template_message = TemplateSendMessage(
    template=MediaTemplate(
        elements=[
            ImageElement(
                facebook_url="https://www.facebook.com/photo.php?fbid=<NUMERIC_ID>",
                buttons=[
                    PostbackAction(title="postback_1", payload="data_1"),
                    URLAction(
                        title="url_1",
                        url="http://example.com/1",
                        webview_height_ratio='full',
                        messenger_extensions=None,
                        fallback_url=None
                    )
                ]
            )
        ]
    )
)

Hints

API Documents

Official Documents

Examples