0

我很难弄清楚如何准确地使用 FacebookGraph ApiWebhooks. 我正在尝试发送和阅读我在 Facebook 上参与的群聊中的消息。我按照步骤在 Developers.Facebook.com 上创建了一个应用程序,并通过了pages_messages. 我生成了一个Page_access_token并将我的应用程序订阅到我的 fb 页面。我想我需要在我的代码中为 Facebook 提供实际的page_access_tokenapp_secret某处,但我遵循的教程对此只字未提。我正在使用 django,下面的代码使用我在网上找到的教程从 Facebook 接收 webhook:

class botView(generic.View):
def get(self, request, *args, **kwargs):
    if self.request.GET['hub.verify_token'] == VERIFY_TOKEN:
        print(self.request.GET['hub.challenge'])
        return HttpResponse(self.request.GET['hub.challenge'], 200)
    else:
        return HttpResponse('Error, invalid token')

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

# Post function to handle Facebook messages
def post(self, request, *args, **kwargs):
    # Converts the text payload into a python dictionary
    incoming_message = json.loads(self.request.body.decode('utf-8'))
    print(incoming_message)
    # 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:
            pass
            # Check to make sure the received call is a message call
            # This might be delivery, optin, postback for other events
            if 'message' in 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("ok", 200)

这是教程的链接

https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok

我可以将测试从 webhook 发送到我的服务器并获得如下响应:

{'entry': [{'time': 1535460973, 'id': '0', 'changed_fields': ['message_sends'], 'uid': '0'}], 'object': 'user'

但是 webhook 提供的相同响应如下所示:

    {
  "field": "message_sends",
  "value": {
    "id": "mid.86753098675309:uuddlrlrbas",
    "message": "I'm changing jobs for the next 4+ years. Wanna be CEO?",
    "from": {
      "id": 44444444,
      "name": "Lizard Zuckerman",
      "email": "zuck@tehfacebook.com"
    },
    "to": {
      "data": [
        {
          "id": 20061985,
          "name": "Bobbert Cruz",
          "email": "bobbert@tehfacebook.com"
        }
      ]
    }
  }
}

Ngrok 确实在我收到测试时显示连接成功,但是当我在我的页面上收到消息时我什么也得不到,即使我订阅了它。

4

0 回答 0