Skip to content

Instantly share code, notes, and snippets.

@nikhilkumarsingh
Created March 16, 2017 11:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nikhilkumarsingh/8f6e109e4968820d37dd27d4afbf72b0 to your computer and use it in GitHub Desktop.
Save nikhilkumarsingh/8f6e109e4968820d37dd27d4afbf72b0 to your computer and use it in GitHub Desktop.
Facebook Messenger Bot tutorial series | A basic echo bot | app.py
import os, sys
from flask import Flask, request
from pymessenger import Bot
app = Flask(__name__)
PAGE_ACCESS_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
bot = Bot(PAGE_ACCESS_TOKEN)
@app.route('/', methods=['GET'])
def verify():
# Webhook verification
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == "hello":
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "Hello world", 200
@app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
log(data)
if data['object'] == 'page':
for entry in data['entry']:
for messaging_event in entry['messaging']:
# IDs
sender_id = messaging_event['sender']['id']
recipient_id = messaging_event['recipient']['id']
if messaging_event.get('message'):
# Extracting text message
if 'text' in messaging_event['message']:
messaging_text = messaging_event['message']['text']
else:
messaging_text = 'no text'
# Echo
response = messaging_text
bot.send_text_message(sender_id, response)
return "ok", 200
def log(message):
print(message)
sys.stdout.flush()
if __name__ == "__main__":
app.run(debug = True, port = 80)
@el0911
Copy link

el0911 commented Apr 5, 2017

tankks

@el0911
Copy link

el0911 commented Apr 5, 2017

for not putting this on th first vid i wont hav learnt anything if u did

@cuonglee
Copy link

Hi nikhilkumarsingh,

Could you show me code of 'pymessenger' class?

Thanks in advance

@supereng
Copy link

Awesome work man !!!

@Dulce06
Copy link

Dulce06 commented Dec 28, 2018

Hi,

I am trying to execute the above code on PyCharm. It's running on the local host. Display's "Hello World" ok.

But when I do a post request on postman, it gives errors. Says "if data['object'] == 'page':
TypeError: 'NoneType' object is not subscriptable"

I want the messages for my facebook page to be displayed in json format and then parse them.

Could you please help me with this.

Many thanks in advance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment