-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
87 lines (66 loc) · 2.35 KB
/
app.py
File metadata and controls
87 lines (66 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from flask import Flask, request
import json
import requests
import os
import sys
from datetime import datetime
PAT_KEY = os.environ.get('PAT_KEY', None)
app = Flask(__name__)
@app.route('/', methods=['GET'])
def verify():
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == PAT_KEY:
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()
print(data)
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
if messaging_event.get("message"):
sender_id = messaging_event["sender"]["id"]
recipient_id = messaging_event["recipient"]["id"]
message_text = messaging_event["message"]["text"]
send_message(sender_id, "roger that!")
if messaging_event.get("delivery"):
pass
if messaging_event.get("optin"):
pass
if messaging_event.get("postback"):
pass
return "ok", 200
def send_message(recipient_id, message_text):
print("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text))
params = {
"access_token": PAT_KEY
}
headers = {
"Content-Type": "application/json"
}
data = json.dumps({
"recipient": {
"id": recipient_id
},
"message": {
"text": message_text
}
})
r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data)
if r.status_code != 200:
print(r.status_code)
print(r.text)
# def print(msg, *args, **kwargs): # simple wrapper for logging to stdout on heroku
# try:
# if type(msg) is dict:
# msg = json.dumps(msg)
# else:
# msg = unicode(msg).format(*args, **kwargs)
# print("{}: {}".format(datetime.now(), msg))
# except UnicodeEncodeError:
# pass # squash logging errors in case of non-ascii text
# sys.stdout.flush()
if __name__ == '__main__':
app.run(debug=True)