Reputation: 638
I've followed this tutorial to implement a Facebook Messenger bot that simply echoes what you type. It hooks up ok with Facebook, but I can't make it work beyond that and I can't find the problem. Can you please help me? This is the code so far (with minor modifications compared with the code in the tutorial).
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()
Upvotes: 0
Views: 502
Reputation: 235
Try placing the entire function
def post_facebook_message(fbid, recevied_message):
....
outside of the BotsView class. If you keep it within the class, it must take in "self" as its first parameter and they must be accessed within the class as
self.post_facebook_message(.....)
However, it might not be the best thing to put this function in the Django View Class.
p.s - Thanks for this, I will update the tutorial to make this point explicit.
Upvotes: 1