Last active
April 27, 2016 09:28
-
-
Save mrtopf/91b2b3fbe970c7b4849fc77a8272a6d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask import request | |
import requests | |
import json | |
PAGE_TOKEN="please use your own token here" | |
app = Flask(__name__) | |
@app.route('/testbot', methods=["GET"]) | |
def confirm(): | |
if request.args['hub.verify_token'] == "cd7czs87czds8chsiuh9eh3k3bcjhdbjhb": | |
return request.args['hub.challenge'] | |
return 'Hello World!' | |
@app.route('/testbot', methods=["POST"]) | |
def receive_message(): | |
data = request.json | |
handle_messages(data) | |
return "ok" | |
def handle_messages(data): | |
"""handle all incoming messages""" | |
messaging_events = data['entry'][0]['messaging'] | |
for event in messaging_events: | |
sender_id = event['sender']['id'] | |
# check if we actually have some input | |
if "message" in event and event['message'].get("text","") != "": | |
text = event['message']['text'] | |
# send a simple text reply | |
reply = "Toll, Du hast folgendes gesagt: "+text | |
send_text(sender_id, reply) | |
def send_text(recipient_id, text): | |
"""send a text message to a recipient""" | |
recipient = { 'id' : recipient_id } | |
message = { 'text' : text } | |
payload = { | |
'recipient' : recipient, | |
'message' : message | |
} | |
send(payload) | |
def send(payload): | |
"""send a payload via the graph API""" | |
headers = {'Content-Type': 'application/json'} | |
r = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token="+PAGE_TOKEN, | |
data = json.dumps(payload), | |
headers = headers) | |
if __name__ == '__main__': | |
app.debug = True | |
app.run(port=8888) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment