Skip to content

Instantly share code, notes, and snippets.

@mrtopf
Last active Apr 27, 2016
Embed
What would you like to do?
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