使用FB Messenger和Django的Echo bot

时间:2016-06-05 21:46:41

标签: python django bots messenger

我有以下观点:

import json, requests
from pprint import pprint

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt


def echo(fb_id, received_message):
    post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=EAAPZASejNRr4BACmWieSuuFpTcK9ZCZB7sJzdZCnw0WS3lUI6RXIZArgwt8m8Qg9JMm4GZACyIFPCG0CnubFxxfzzRomplntBHhr4ZCKzupGJZCiLjnw9UrUmgQWbCGXi5at9vZBVVmKFYSGfDZCVoY83KIIO62XiFXAr6Ut2OQIS2aAZDZD'
    reply = json.dumps({
        'recipient': {'id': fb_id},
        'message': {'text': received_message},
    })
    status = requests.post(post_message_url, headers={'Content-Type': 'application/json'}, data=reply)
    pprint(status.json())


class FbBotView(View):

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return View.dispatch(self, self.request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        if self.request.GET['hub.verify_token'] == '25461261':
            return HttpResponse(request.GET['hub.challenge'])
        else:
            return HttpResponse('Error: Incorrect verification token')

    def post(self, request, *args, **kwargs):
        incoming_message = json.loads(self.request.body.decode('utf-8'))

        for entry in incoming_message['entry']:
            for message in entry['messaging']:
                if 'message' in message:
                    pprint(message)
                    echo(message['sender']['id'], message['message']['text'])

        return HttpResponse()

给出here的教程说,echo函数应该在FbBotView类中。果然,当我将echo函数放在类FbBotView中时,bot无法回显。为什么会这样?

1 个答案:

答案 0 :(得分:1)

如果我清楚地阅读教程,它会在外面说但不在里面......

# yomamabot/fb_yomamabot/views.py
# This function should be outside the BotsView class
def post_facebook_message(fbid, recevied_message):           
    post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<page-access-token>' 
    response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":recevied_message}})
    status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
    pprint(status.json())

我认为原因是你在Django中使用class-based views而不是基于函数的视图,这就是为什么你不能在FbBotView中使用自定义方法。