我是python开发人员,并且正在使用python开发Facebook机器人。它运行良好,没有出现以下问题:
class FacebookBotViewSet(generic.View):
def get(self, request, *args, **kwargs):
if self.request.GET['hub.verify_token'] == settings.FACEBOOK_VERIFY_TOKEN:
return HttpResponse(self.request.GET['hub.challenge'])
else:
return HttpResponse('Error, invalid token')
# Post function to handle Facebook messages
def post(self, request, *args, **kwargs):
from ai_api.services.widget import WidgetService
fb_request_object = FBRequestObject(self.request.body)
fb_messenger_objects = fb_request_object.get_messenger_objects()
for fb_messenger_object in fb_messenger_objects:
fb_page_id = fb_messenger_object.get_page_id()
msg_text = fb_messenger_object.get_text()
msg_mid = fb_messenger_object.get_mid()
sender_id = fb_messenger_object.get_sender_id()
is_get_started = fb_messenger_object.is_post_back() and msg_text == FacebookPostBack.GET_STARTED
if sender_id and ((msg_text and msg_mid) or is_get_started):
widget = WidgetService.get_by_fb_page_id(fb_page_id)
if widget:
fb_page_token = widget.fb_access_token
FacebookService.post_facebook_message(fb_page_token, sender_id, '')
is_continue = True
if is_get_started:
try:
msg_text = FacebookService.get_fb_name(sender_id, fb_page_token)
except Exception as e:
is_continue = False
reply_text = e.error.get('message')
FacebookService.post_facebook_message(fb_page_token, sender_id, reply_text)
if is_continue:
webhook_callback = PBLWebhookViewSet.as_view({'post': 'callback'})
kwargs = {
"sender_id": sender_id,
"text": msg_text,
"page_id": fb_page_id,
"web_id": widget.id,
"mid": msg_mid,
"is_get_started": is_get_started,
"source": ApplySource.FACEBOOK_MESSAGER
}
response = webhook_callback(self.request, **kwargs)
if response and response.data:
reply_text = response.data.get('body', '')
kb_message = response.data.get('kb_message', '')
sender_id = fb_messenger_object.get_sender_id()
if reply_text:
FacebookService.reply_facebook_message(fb_page_token, sender_id, reply_text)
if kb_message:
FacebookService.reply_facebook_message(fb_page_token, sender_id, kb_message)
return HttpResponse()
您可以看到post方法,每当Facebook用户向我的页面发送消息时,该方法就会被调用。但是,当获取响应消息的处理花费太多时间(约10秒)时,就会一次又一次调用post方法。我的意思是,当我的页面收到新消息时,该方法将被调用多次。这是错误的。任何人都可以向我展示如何防止该问题,然后仅对每条消息调用一次回发方法。谢谢