PyMessager es una API de Python para Facebook Messenger y un proyecto de muestra para demostrar cómo desarrollar un chatbot en Facebook Messenger.
Hay tutoriales completos sobre Desarrollar un bot de Facebook usando Python y Chatbot: de 0 a 1, donde puede encontrar información más detallada para configurar y desarrollar.
Para instalar PyMessager, simplemente ejecute:
$ pip install pymessager
o instalar desde el repositorio:
$ git clone [email protected]:enginebai/PyMessager.git
$ cd PyMessager
$ pip install -r requirements.txt
from pymessager . message import Messager , ... # something else you need
Puedes inicializar un cliente de mensajería a través de un token de acceso de Facebook desde la consola del desarrollador:
from pymessager . message import Messager
client = Messager ( config . facebook_access_token )
El siguiente código se utiliza para crear un receptor de mensajes; hay tres pasos principales para preparar su bot:
@ app . route ( API_ROOT + FB_WEBHOOK , methods = [ "GET" ])
def fb_webhook ():
verification_code = 'I_AM_VERIFICIATION_CODE'
verify_token = request . args . get ( 'hub.verify_token' )
if verification_code == verify_token :
return request . args . get ( 'hub.challenge' )
@ app . route ( API_ROOT + FB_WEBHOOK , methods = [ 'POST' ])
def fb_receive_message ():
message_entries = json . loads ( request . data . decode ( 'utf8' ))[ 'entry' ]
for entry in message_entries :
for message in entry [ 'messaging' ]:
if message . get ( 'message' ):
print ( "{sender[id]} says {message[text]}" . format ( ** message ))
return "Hi"
if __name__ == '__main__' :
context = ( 'ssl/fullchain.pem' , 'ssl/privkey.pem' )
app . run ( host = '0.0.0.0' , debug = True , ssl_context = context )
Existen varios tipos de mensaje: text
, image
, quick replies
, button template
o generic template
. API proporciona diferentes clases para generar la plantilla de mensaje.
Envíe un texto simple o una imagen a un destinatario, solo asegúrese de que la URL de la imagen sea un enlace válido.
client . send_text ( user_id , "Hello, I'm enginebai." )
client . send_image ( user_id , "http://image-url.jpg" )
La clase QuickReply(title, payload, image_url, content_type)
define botones presentes para el usuario en respuesta a un mensaje.
Parámetro | Descripción | Requerido |
---|---|---|
title | El título del botón | Y |
payload | La cadena de carga útil del clic | Y |
image_url | La URL de la imagen del icono | norte |
content_type | TEXT o LOCATION | Y |
client . send_quick_replies ( user_id , "Help" , [
QuickReply ( "Projects" , Intent . PROJECT ),
QuickReply ( "Blog" , Intent . BLOG ),
QuickReply ( "Contact Me" , Intent . CONTACT_ME )
])
La clase ActionButton(button_type, title, url, payload)
define una plantilla de botón que contiene un texto y un archivo adjunto de botones para solicitar información del usuario.
Parámetro | Descripción | Requerido |
---|---|---|
button_type | WEB_URL o POSTBACK | Y |
title | El título del botón | Y |
url | El enlace | Sólo si button_type es url |
payload | La cadena de carga útil del clic | Sólo si button_type es POSTBACK |
client . send_buttons ( user_id , "You can find me with below" , [
ActionButton ( ButtonType . WEB_URL , "Blog" , "http://blog.enginebai.com" ),
ActionButton ( ButtonType . POSTBACK , "Email" , Intent . EMAIL )
])
La clase GenericElement(title, subtitle, image_url, buttons)
define un carrusel de elementos desplazable horizontal, cada uno compuesto por una imagen adjunta, una breve descripción y botones para solicitar información del usuario.
Parámetro | Descripción | Requerido |
---|---|---|
title_text | El título principal del mensaje. | Y |
subtitle_text | El subtítulo del mensaje, déjalo vacío si no lo necesitas | norte |
button_list | La lista de ActionButton | Y |
project_list = []
for project_id , project in projects . items ():
project_list . append ( GenericElement (
project [ "title" ],
project [ "description" ],
config . api_root + project [ "image_url" ], [
ActionButton ( ButtonType . POSTBACK ,
self . _get_string ( "button_more" ),
# Payload use Intent for the beginning
payload = Intent . PROJECTS . name + project_id )
]))
client . send_generic ( user_id , project_list )
Antes de que su chatbot comience a recibir mensajes, debe suscribir la aplicación a su página de chatbot. Para suscribir una página, simplemente llámala:
client . subscribe_to_page ()
El texto de saludo se mostrará la primera vez que abra este chatbot solo en un dispositivo móvil. La carga útil es el disparador cuando los usuarios hacen clic en el botón "Comenzar".
client . set_greeting_text ( "Hi, this is Engine Bai. Nice to meet you!" )
client . set_get_started_button_payload ( "HELP" ) # Specify a payload string.
No dude en enviar informes de errores o solicitudes de funciones y asegúrese de leer la guía de contribución antes de abrir cualquier problema.
feature
/ bug
).Lea más sobre cómo contribuir.
The MIT License (MIT)
Copyright © 2017 Engine Bai.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.