Skip to content

Instantly share code, notes, and snippets.

@javaguirre
Last active September 1, 2017 08:01
Show Gist options
  • Save javaguirre/2bdb8df879513aaf6fdb17d9b8202a06 to your computer and use it in GitHub Desktop.
Save javaguirre/2bdb8df879513aaf6fdb17d9b8202a06 to your computer and use it in GitHub Desktop.
Silly and dirty example to test Messenger Facebook templates

Quick and dirty solution to test different kinds of Facebook messenger templates.

pip install -r requirements.txt

You'll need to set the environment variables PAGE_ACCESS_TOKEN and VERIFY_TOKEN.

You'll need something like ngrok to set a public url so you receive Facebook webhook links.

https://ngrok.com/

Once installed you'll need to set it to the port 5000 (default for Flask).

ngrok http 5000

An alternative is using pagekite.

https://pagekite.net/

You can launch it with python app.py.

Let me know if you need anything! :-)

import os
import sys
import json
import requests
from flask import Flask, request
app = Flask(__name__)
def whitelist(url):
params = {
"access_token": os.environ["PAGE_ACCESS_TOKEN"]
}
headers = {
"Content-Type": "application/json"
}
data = {
'setting_type': 'domain_whitelisting',
'whitelisted_domains': [url],
'domain_action_type': 'add'
}
r = requests.post(
"https://graph.facebook.com/v2.6/me/thread_settings",
params=params,
headers=headers,
json=data)
if r.status_code != 200:
log(r.status_code)
log(r.text)
def process_message(text):
if text == 'template':
return None, {'attachment': {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": "Welcome to Peter\'s Hats",
"image_url": "https://javaguirre.me/content/images/2015/11/ample-1.png",
"subtitle": "We\'ve got the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://javaguirre.me",
"messenger_extensions": True,
"webview_height_ratio": "tall",
"fallback_url": "https://javaguirre.me/about"
},
"buttons": [
{
"type": "postback",
"title": "View Website",
"payload": "payme"
},
{
"type": "postback",
"title": "Start Chatting",
"payload": "DEVELOPER_DEFINED_PAYLOAD"
}
]
}
]
}
}}
elif text == 'quick':
return 'Select', {"quick_replies": [
{
"content_type": "text",
"title": "Red",
"payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
},
{
"content_type": "text",
"title": "Green",
"payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
}
]
}
elif text == 'image':
return None, {
"attachment": {
"type": "image",
"payload": {
"url": "https://javaguirre.me/content/images/2015/11/ample-1.png"
}
}
}
else:
return 'ok', None
@app.route('/', methods=['GET'])
def verify():
# when the endpoint is registered as a webhook, it must echo back
# the 'hub.challenge' value it receives in the query arguments
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "Hello world", 200
@app.route('/', methods=['POST'])
def webhook():
# endpoint for processing incoming messaging events
data = request.get_json()
log(data) # you may not want to log every incoming message in production, but it's good for testing
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
if messaging_event.get("message"): # someone sent us a message
sender_id = messaging_event["sender"]["id"] # the facebook ID of the person sending you the message
recipient_id = messaging_event["recipient"]["id"] # the recipient's ID, which should be your page's facebook ID
message_text = messaging_event["message"]["text"] # the message's text
send_message(sender_id, *process_message(message_text))
if messaging_event.get("delivery"): # delivery confirmation
pass
if messaging_event.get("optin"): # optin confirmation
pass
if messaging_event.get("postback"): # user clicked/tapped "postback" button in earlier message
pass
return "ok", 200
def send_message(recipient_id, message_text, metadata=None):
log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text))
params = {
"access_token": os.environ["PAGE_ACCESS_TOKEN"]
}
headers = {
"Content-Type": "application/json"
}
data = {
"recipient": {
"id": recipient_id
},
"message": {
}
}
whitelist('https://javaguirre.me')
if metadata:
data['message'] = metadata
if message_text:
data['message']['text'] = message_text
r = requests.post(
"https://graph.facebook.com/v2.6/me/messages",
params=params,
headers=headers,
json=data)
if r.status_code != 200:
log(r.status_code)
log(r.text)
def log(message): # simple wrapper for logging to stdout on heroku
print str(message)
sys.stdout.flush()
if __name__ == '__main__':
app.run(debug=True)
Flask==0.11.1
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.11.10
click==6.6
gunicorn==19.6.0
itsdangerous==0.24
requests==2.10.0
wsgiref==0.1.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment