PyMessager は Facebook Messenger 用の Python API であり、Facebook Messenger でチャットボットを開発する方法を示すサンプル プロジェクトです。
完全なチュートリアルは「Python とチャットボットを使用して 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 )
次のコードはメッセージ レシーバーを構築するために使用されます。ボットを準備するには、主に 3 つの手順があります。
@ 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 | ボタンのタイトル | Y |
payload | クリックペイロード文字列 | Y |
image_url | アイコン画像のURL | N |
content_type | TEXT またはLOCATION | Y |
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 | Y |
title | ボタンのタイトル | Y |
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 | メッセージのメインタイトル | Y |
subtitle_text | メッセージのサブタイトル。必要ない場合は空白のままにしてください | N |
button_list | 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 )
チャットボットがメッセージの受信を開始する前に、アプリケーションをチャットボット ページに登録する必要があります。ページを購読するには、それを呼び出すだけです:
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.