Skip to content

Instantly share code, notes, and snippets.

@madewulf
Last active April 18, 2016 08:30
Show Gist options
  • Save madewulf/7b6f2c2d702b6069fe9dd5b566de26c4 to your computer and use it in GitHub Desktop.
Save madewulf/7b6f2c2d702b6069fe9dd5b566de26c4 to your computer and use it in GitHub Desktop.
A POC Python echo bot over FB messenger API using Flask and Requests
from flask import Flask
from flask import request
import json
import requests
PAGE_ACCESS_TOKEN = ""
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def bot():
#handling authentication challenges
challenge = request.args.get('hub.challenge', '')
if challenge:
return challenge
body = request.get_json()
# example message received : {u'entry': [{u'messaging': [{u'timestamp': 1460910258649, u'message': {u'text': u'ddd', u'mid': u'mid.1460910258643:c89752451d7659ad12', u'seq': 27}, u'recipient': {u'id': 1287972411254583}, u'sender': {u'id': 1068438169896529}}], u'id': 1287972411254583, u'time': 1460910258679}], u'object': u'page'}
try:
#parsing the received message (it will fail if it is not just text)
sender_id = body['entry'][0]['messaging'][0]['sender']['id']
text = body['entry'][0]['messaging'][0]['message']['text']
#building the response
response_content = {
"recipient": {
"id": sender_id
},
"message": {
"text": text
}
}
headers = {"Content-Type": "application/json"}
url = "https://graph.facebook.com/v2.6/me/messages?access_token=%s" % PAGE_ACCESS_TOKEN
#sending the response
r = requests.post(url, data=json.dumps(response_content), headers=headers)
print r.text
except:
print "some exception happened"
return "ok"
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment