Une bibliothèque Python pour utiliser l'API de la plateforme Facebook Messenger (Bibliothèque Python Facebook Chat & Chatbot) Toutes les fonctionnalités de l'API de la plateforme Facebook Messenger sont prises en charge
pip install fbmq
comment gérer les messages de l'utilisateur vers la page Facebook
from flask import Flask , request
from fbmq import Page
page = Page ( PAGE_ACCESS_TOKEN )
@ app . route ( '/webhook' , methods = [ 'POST' ])
def webhook ():
page . handle_webhook ( request . get_data ( as_text = True ))
return "ok"
@ page . handle_message
def message_handler ( event ):
""":type event: fbmq.Event"""
sender_id = event . sender_id
message = event . message_text
page . send ( sender_id , "thank you! your message is '%s'" % message )
@ page . after_send
def after_send ( payload , response ):
""":type payload: fbmq.Payload"""
print ( "complete" )
Une spécification en détail - https://developers.facebook.com/docs/messenger-platform/webhook-reference
@page.handle_message
- Ce rappel se produira lorsqu'un message aura été envoyé à votre page. ( quick reply
est également traitée ici)
@page.handle_echo
- Ce rappel se produira lorsqu'un message aura été envoyé par votre page
@page.handle_delivery
- Ce rappel se produira lorsqu'un message envoyé par une page a été remis.
@page.handle_optin
- Ce rappel se produira lorsque le plugin Send-to-Messenger aura été exploité
@page.handle_postback
- Les publications se produisent lorsqu'un bouton de publication, un bouton Commencer, un menu persistant ou un message structuré est enfoncé.
@page.handle_read
- Ce rappel se produira lorsqu'un message envoyé par une page a été lu par l'utilisateur.
@page.handle_account_linking
- Ce rappel se produira lorsque l'appel à l'action du compte lié ou du compte dissocié aura été activé.
@page.after_send
- Ce rappel se produira lorsque la fonction page.send aura été appelée.
event.sender_id
str : identifiant de l'expéditeur du message, identifiant de l'utilisateur
event.recipient_id
str : identifiant du destinataire du message, identifiant de la page
event.timestamp
number : horodatage de la réception du message
event.message
dict : dict de message reçu. plus de détails
event.message_text
str : event.message.get('text')
event.message_attachments
chaîne : event.message.get('attachments')
event.quick_reply
dict : dict de réponse rapide reçu. plus de détails
event.quick_reply_payload
str : `event.quick_reply.get('payload')
event.postback
dict : dict de publication reçu. plus de détails
event.postback_payload
str : `event.postback.get('payload')
event.optin
dict : dict reçu. plus de détails
event.account_linking
dict : dict reçu. plus de détails
event.delivery
dict : dict reçu. plus de détails
event.read
dict : dict reçu. plus de détails
event.is_*
bool - Vrai si le type d'événement est valide
page = fbmq . Page ( PAGE_ACCESS_TOKEN , after_send = after_send )
@ app . route ( '/webhook' , methods = [ 'POST' ])
def webhook ():
page . handle_webhook ( request . get_data ( as_text = True ),
message = message_handler )
return "ok"
def message_handler ( event ):
""":type event: fbmq.Event"""
sender_id = event . sender_id
message = event . message_text
page . send ( sender_id , "thank you! your message is '%s'" % message )
def after_send ( payload , response ):
""":type event: fbmq.Payload"""
print ( "complete" )
comment envoyer un message de la page Facebook à l'utilisateur
from fbmq import Attachment , Template , QuickReply , Page
page . send ( recipient_id , "hello world!" )
Prise en charge jpg, png, gif
page . send ( recipient_id , Attachment . Image ( image_url ))
page . send ( recipient_id , Attachment . Audio ( audio_url ))
page . send ( recipient_id , Attachment . Video ( video_url ))
page . send ( recipient_id , Attachment . File ( file_url ))
quick_replies = [
QuickReply ( title = "Action" , payload = "PICK_ACTION" ),
QuickReply ( title = "Comedy" , payload = "PICK_COMEDY" )
]
# you can use a dict instead of a QuickReply class
#
# quick_replies = [{'title': 'Action', 'payload': 'PICK_ACTION'},
# {'title': 'Comedy', 'payload': 'PICK_COMEDY'}]
page . send ( recipient_id ,
"What's your favorite movie genre?" ,
quick_replies = quick_replies ,
metadata = "DEVELOPER_DEFINED_METADATA" )
vous pouvez définir facilement une méthode de rappel de réponse rapide.
@ page . callback ([ 'PICK_ACTION' , 'PICK_COMEDY' ])
def callback_picked_genre ( payload , event ):
print ( payload , event )
# Also supported regex, it works corretly
# @page.callback(['PICK_(.+)'])
si vous souhaitez gérer uniquement le rappel quick_reply sans publication de bouton
@ page . callback ([ 'PICK_ACTION' , 'PICK_COMEDY' ], types = [ 'QUICK_REPLY' ])
page . typing_on ( recipient_id )
page . typing_off ( recipient_id )
buttons = [
Templates . ButtonWeb ( "Open Web URL" , "https://www.oculus.com/en-us/rift/" ),
Templates . ButtonPostBack ( "trigger Postback" , "DEVELOPED_DEFINED_PAYLOAD" ),
Templates . ButtonPhoneNumber ( "Call Phone Number" , "+16505551234" )
]
# you can use a dict instead of a Button class
#
# buttons = [{'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'},
# {'type': 'postback', 'title': 'trigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'},
# {'type': 'phone_number', 'title': 'Call Phone Number', 'value': '+16505551234'}]
page . send ( recipient_id , Template . Buttons ( "hello" , buttons ))
vous pouvez définir facilement une méthode de postback de bouton (elle ne fonctionne que pour les boutons de type postback).
@ page . callback ([ 'DEVELOPED_DEFINED_PAYLOAD' ])
def callback_clicked_button ( payload , event ):
print ( payload , event )
# Also supported regex, it works corretly
# @page.callback(['DEVELOPED_DEFINE(.+)'])
si vous souhaitez gérer uniquement la publication du bouton sans rappel quick_reply
@ page . callback ([ 'DEVELOPED_DEFINED_PAYLOAD' ], types = [ 'POSTBACK' ])
page . send ( recipient_id , Template . Generic ([
Template . GenericElement ( "rift" ,
subtitle = "Next-generation virtual reality" ,
item_url = "https://www.oculus.com/en-us/rift/" ,
image_url = CONFIG [ 'SERVER_URL' ] + "/assets/rift.png" ,
buttons = [
Template . ButtonWeb ( "Open Web URL" , "https://www.oculus.com/en-us/rift/" ),
Template . ButtonPostBack ( "tigger Postback" , "DEVELOPED_DEFINED_PAYLOAD" ),
Template . ButtonPhoneNumber ( "Call Phone Number" , "+16505551234" )
]),
Template . GenericElement ( "touch" ,
subtitle = "Your Hands, Now in VR" ,
item_url = "https://www.oculus.com/en-us/touch/" ,
image_url = CONFIG [ 'SERVER_URL' ] + "/assets/touch.png" ,
buttons = [
Template . ButtonWeb ( "Open Web URL" , "https://www.oculus.com/en-us/rift/" ),
Template . ButtonPostBack ( "tigger Postback" , "DEVELOPED_DEFINED_PAYLOAD" ),
Template . ButtonPhoneNumber ( "Call Phone Number" , "+16505551234" )
])
]))
element = Template . ReceiptElement ( title = "Oculus Rift" ,
subtitle = "Includes: headset, sensor, remote" ,
quantity = 1 ,
price = 599.00 ,
currency = "USD" ,
image_url = CONFIG [ 'SERVER_URL' ] + "/assets/riftsq.png"
)
address = Template . ReceiptAddress ( street_1 = "1 Hacker Way" ,
street_2 = "" ,
city = "Menlo Park" ,
postal_code = "94025" ,
state = "CA" ,
country = "US" )
summary = Template . ReceiptSummary ( subtotal = 698.99 ,
shipping_cost = 20.00 ,
total_tax = 57.67 ,
total_cost = 626.66 )
adjustment = Template . ReceiptAdjustment ( name = "New Customer Discount" , amount = - 50 )
page . send ( recipient_id , Template . Receipt ( recipient_name = 'Peter Chang' ,
order_number = '1234' ,
currency = 'USD' ,
payment_method = 'Visa 1234' ,
timestamp = "1428444852" ,
elements = [ element ],
address = address ,
summary = summary ,
adjustments = [ adjustment ]))
prend en charge notification_type en option
NotificationType.REGULAR (default)
, NotificationType.SILENT_PUSH
, NotificationType.NO_PUSH
page.send(recipient_id, 'hello', notification_type=NotificationType.NO_PUSH)
vous pouvez définir une fonction de rappel sur chaque page.send
def callback(payload, response):
print('response : ' + response.text)
page.send(recipient_id, 'hello', callback=callback)
page . greeting ( "Welcome!" )
page . show_starting_button ( "START_PAYLOAD" )
@ page . callback ([ 'START_PAYLOAD' ])
def start_callback ( payload , event ):
print ( "Let's start!" )
page . show_persistent_menu ([ Template . ButtonPostBack ( 'MENU1' , 'MENU_PAYLOAD/1' ),
Template . ButtonPostBack ( 'MENU2' , 'MENU_PAYLOAD/2' )])
@ page . callback ([ 'MENU_PAYLOAD/(.+)' ])
def click_persistent_menu ( payload , event ):
click_menu = payload . split ( '/' )[ 1 ]
print ( "you clicked %s menu" % click_menu )
page_id = page.page_id
page_name = page.page_name
user_profile = page.get_user_profile(event.sender_id) # return dict
print(user_profile)
#{"first_name":"...", "last_name":"...", "profile_pic":"...", "locale":"...", "timezone":9, "gender":"..."}
cd example
virtualenv env
source env/bin/activate
pip install -r requirements.txt
python server.py