PyMessager는 Facebook 메신저용 Python API이자 Facebook 메신저에서 챗봇을 개발하는 방법을 보여주는 샘플 프로젝트입니다.
전체 튜토리얼은 Python 및 Chatbot을 사용하여 Facebook 봇 개발: 0에서 1까지에서 설정 및 개발에 대한 자세한 정보를 찾을 수 있습니다.
PyMessager를 설치하려면 다음을 실행하세요.
$ pip install pymessager
또는 저장소에서 설치하십시오.
$ git clone [email protected]:enginebai/PyMessager.git
$ cd PyMessager
$ pip install -r requirements.txt
from pymessager . message import Messager , ... # something else you need
개발자 콘솔에서 Facebook 액세스 토큰을 통해 메시지 클라이언트를 초기화할 수 있습니다.
from pymessager . message import Messager
client = Messager ( config . facebook_access_token )
다음 코드는 메시지 수신기를 구축하는 데 사용됩니다. 봇을 준비하는 세 가지 주요 단계가 있습니다.
@ 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 )
메시지에는 text
, image
, quick replies
, button template
또는 generic template
등 여러 유형이 있습니다. API는 메시지 템플릿을 생성하기 위한 다양한 클래스를 제공합니다.
간단한 텍스트나 이미지를 수신자에게 보내세요. 이미지 URL이 유효한 링크인지 확인하세요.
client . send_text ( user_id , "Hello, I'm enginebai." )
client . send_image ( user_id , "http://image-url.jpg" )
QuickReply(title, payload, image_url, content_type)
클래스는 메시지에 대한 응답으로 사용자에게 표시되는 버튼을 정의합니다.
매개변수 | 설명 | 필수의 |
---|---|---|
title | 버튼 제목 | 와이 |
payload | 클릭 페이로드 문자열 | 와이 |
image_url | 아이콘 이미지 URL | N |
content_type | TEXT 또는 LOCATION | 와이 |
client . send_quick_replies ( user_id , "Help" , [
QuickReply ( "Projects" , Intent . PROJECT ),
QuickReply ( "Blog" , Intent . BLOG ),
QuickReply ( "Contact Me" , Intent . CONTACT_ME )
])
ActionButton(button_type, title, url, payload)
클래스는 사용자에게 입력을 요청하기 위한 텍스트 및 버튼 첨부 파일이 포함된 버튼 템플릿을 정의합니다.
매개변수 | 설명 | 필수의 |
---|---|---|
button_type | WEB_URL 또는 POSTBACK | 와이 |
title | 버튼 제목 | 와이 |
url | 링크 | button_type 이 url 인 경우에만 |
payload | 클릭 페이로드 문자열 | button_type 이 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 )
])
GenericElement(title, subtitle, image_url, buttons)
클래스는 가로로 스크롤 가능한 항목의 캐러셀을 정의합니다. 각 항목은 이미지 첨부 파일, 간단한 설명, 사용자 입력을 요청하는 버튼으로 구성됩니다.
매개변수 | 설명 | 필수의 |
---|---|---|
title_text | 메시지 메인 제목 | 와이 |
subtitle_text | 메시지 자막은 필요없으시면 비워두세요 | N |
button_list | ActionButton 목록 | 와이 |
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 )
챗봇이 메시지 수신을 시작하기 전에 애플리케이션을 챗봇 페이지에 구독해야 합니다. 페이지를 구독하려면 다음과 같이 호출하세요.
client . subscribe_to_page ()
인사말 텍스트는 모바일에서만 이 챗봇을 처음 열 때 표시됩니다. 페이로드는 사용자가 "시작하기" 버튼을 클릭할 때 트리거됩니다.
client . set_greeting_text ( "Hi, this is Engine Bai. Nice to meet you!" )
client . set_get_started_button_payload ( "HELP" ) # Specify a payload string.
버그 보고서나 기능 요청을 자유롭게 제출하고 이슈를 열기 전에 기여 지침을 읽어보세요.
feature
/ bug
)이 있는 버그 보고서를 엽니다.기여에 대해 자세히 알아보세요.
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.