2016-04-15 8 views

答えて

3

私は先に進んで自分自身を移植しました。私は富を分かち合うべきだと思った。 "あなたに!" を持つすべてのメッセージに、このスニペットの応答:

import json 
import requests 
from django.views.decorators.csrf import csrf_exempt 

FB_MESSENGER_ACCESS_TOKEN = "<Your Access Token>" 


def respond_FB(sender_id, text): 
    json_data = { 
     "recipient": {"id": sender_id}, 
     "message": {"text": text + " to you!"} 
    } 
    params = { 
     "access_token": FB_MESSENGER_ACCESS_TOKEN 
    } 
    r = requests.post('https://graph.facebook.com/v2.6/me/messages', json=json_data, params=params) 
    print(r, r.status_code, r.text) 

#this allows the requst to come in without requiring CSRF token 
@csrf_exempt 
def fb_webhook(request): 
    if request.method == "GET": 
     if (request.GET.get('hub.verify_token') == 'this_is_a_verify_token_created_by_sean'): 
      return HttpResponse(request.GET.get('hub.challenge')) 
     return HttpResponse('Error, wrong validation token') 

    if request.method == "POST": 
     body = request.body 
     print("BODY", body) 
     messaging_events = json.loads(body.decode("utf-8")) 
     print("JSON BODY", body) 
     sender_id = messaging_events["entry"][0]["messaging"][0]["sender"]["id"] 
     message = messaging_events["entry"][0]["messaging"][0]["message"]["text"] 
     respond_FB(sender_id, message) 
     return HttpResponse('Received.') 

And here is the FB Messenger Chatbot port on Gist

+0

ありがとうSean! 'r = requests.post( 'https://graph.facebook.com/v2.6/me/messages'、json = json_data、params = params)の' urllib'に相当するものは何でしょうか? –

+0

このサイトhttp://buddylindsey.com/basic-urllib-get-and-post-with-and-without-data/は、このテーマに関する情報を提供しています。私は最終的なコードが次のようになると思われます。 data = urllib.urlencode(json_data); u = urllib.urlopen( "https://graph.facebook.com/v2.6/me/messages?access_token = [access_token]"、data); – Sean

+0

ありがとうございます!私はGAE上でコードを実行しているので、 '要求'は使用できません。あなたが指摘したコードを使用したが、何とか「Bad Request 400」という結果に終わった。どんなアイデアが間違っているのでしょうか? –

1

私はFacebookのメッセンジャープラットフォーム用のPythonクライアントを書いた:messengerbot

1

これはfbmq libraryそれを使用してPythonのサンプルです私の作品:

エコー例:

from flask import Flask, request 
from fbmq import Page 

page = fbmq.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): 
    page.send(event.sender_id, event.message_text) 
関連する問題