PyMessager é uma API Python para Facebook Messenger e um projeto de exemplo para demonstrar como desenvolver um chatbot no Facebook Messenger.
Os tutoriais completos estão em Desenvolva um bot do Facebook usando Python e Chatbot: de 0 a 1, onde você pode encontrar informações mais detalhadas para configurar e desenvolver.
Para instalar o PyMessager, basta executar:
$ pip install pymessager
ou instale a partir do repositório:
$ git clone [email protected]:enginebai/PyMessager.git
$ cd PyMessager
$ pip install -r requirements.txt
from pymessager . message import Messager , ... # something else you need
Você pode inicializar um cliente de mensagem por meio de um token de acesso do Facebook no console do desenvolvedor:
from pymessager . message import Messager
client = Messager ( config . facebook_access_token )
O código a seguir é usado para construir um receptor de mensagens. Existem três etapas principais para preparar seu 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 )
Existem vários tipos de mensagem: text
, image
, quick replies
, button template
ou generic template
. A API fornece diferentes classes para gerar o modelo de mensagem.
Envie um texto simples ou uma imagem para um destinatário, apenas certifique-se de que o URL da imagem seja um link válido.
client . send_text ( user_id , "Hello, I'm enginebai." )
client . send_image ( user_id , "http://image-url.jpg" )
A classe QuickReply(title, payload, image_url, content_type)
define botões de presente para o usuário em resposta a uma mensagem.
Parâmetro | Descrição | Obrigatório |
---|---|---|
title | O título do botão | S |
payload | A string de carga de clique | S |
image_url | O URL da imagem do ícone | N |
content_type | TEXT ou LOCATION | S |
client . send_quick_replies ( user_id , "Help" , [
QuickReply ( "Projects" , Intent . PROJECT ),
QuickReply ( "Blog" , Intent . BLOG ),
QuickReply ( "Contact Me" , Intent . CONTACT_ME )
])
A classe ActionButton(button_type, title, url, payload)
define o modelo de botão que contém um anexo de texto e botões para solicitar entrada do usuário.
Parâmetro | Descrição | Obrigatório |
---|---|---|
button_type | WEB_URL ou POSTBACK | S |
title | O título do botão | S |
url | A ligação | Somente se button_type for url |
payload | A string de carga de clique | Somente se button_type for 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 )
])
A classe GenericElement(title, subtitle, image_url, buttons)
define um carrossel horizontal de itens com rolagem, cada um composto por um anexo de imagem, uma breve descrição e botões para solicitar entrada do usuário.
Parâmetro | Descrição | Obrigatório |
---|---|---|
title_text | O título principal da mensagem | S |
subtitle_text | O subtítulo da mensagem, deixe em branco se não precisar | N |
button_list | A lista de ActionButton | S |
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 do seu chatbot começar a receber mensagens, você deve inscrever o aplicativo na página do seu chatbot. Para assinar uma página, basta chamá-la:
client . subscribe_to_page ()
O texto de saudação será exibido na primeira vez que você abrir este chatbot apenas no celular. A carga útil é o gatilho quando os usuários clicam no botão "Começar".
client . set_greeting_text ( "Hi, this is Engine Bai. Nice to meet you!" )
client . set_get_started_button_payload ( "HELP" ) # Specify a payload string.
Sinta-se à vontade para enviar relatórios de bugs ou solicitações de recursos e certifique-se de ler as diretrizes de contribuição antes de abrir qualquer problema.
feature
/ bug
).Leia mais sobre como 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.