Facebook messenger机器人不发送消息(Python / Django)

时间:2016-05-03 11:37:16

标签: python django facebook facebook-graph-api

我跟着this tutorial实施了一个Facebook Messenger机器人,它简单地回应了你输入的内容。它可以与Facebook联系起来,但我不能让它超越它,我无法找到问题。你能帮我么?这是到目前为止的代码(与教程中的代码相比进行了少量修改)。

class BotsView(generic.View):
    def get(self, request, *args, **kwargs):
        if self.request.GET.get('hub.verify_token') == '1111111111':
            return HttpResponse(self.request.GET.get('hub.challenge'))
        else:
            return HttpResponse('Error, invalid token')

    def post_facebook_message(fbid, recevied_message):           
        post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<access-token>' 
        response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":recevied_message}})
        requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
        return HttpResponse()

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

    def post(self, request, *args, **kwargs):
        # Converts the text payload into a python dictionary
        incoming_message = json.loads(self.request.body)
        # Facebook recommends going through every entry since they might send
        # multiple messages in a single call during high load
        for entry in incoming_message['entry']:
            for message in entry['messaging']:
                # Check to make sure the received call is a message call
                # This might be delivery, optin, postback for other events 
                if message.has_key('message'):
                    # Print the message to the terminal
                    # pprint(message) 
                    # Assuming the sender only sends text. Non-text messages like stickers, audio, pictures
                    # are sent as attachments and must be handled accordingly. 
                    post_facebook_message(message['sender']['id'], message['message']['text'])     
        return HttpResponse()

1 个答案:

答案 0 :(得分:1)

尝试放置整个功能

def post_facebook_message(fbid, recevied_message): 
  ....

在BotsView类之外。如果你将它保留在类中,它必须将“self”作为其第一个参数,并且必须在类中访问它们

self.post_facebook_message(.....)

但是,将此函数放在Django View类中可能不是最好的选择。

p.s - 感谢您,我将更新教程以明确这一点。