-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
66 lines (45 loc) · 1.66 KB
/
main.py
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
# -*- coding: utf-8 -*-
import json, urllib
from flask import Flask, request, abort
import urlfetch
app = Flask(__name__)
access_token = 'EAAW895WLezkBAGisDrIsZBuazNgk2Ll8fnpjbtg1wXOrJu3aYyFVLrCg3ZABUD3S70vEZAWHsbeYR4lKSm8mrbIdkZAimsAo9FHEHkbZCZBW89Wy56mYWlDyTmD5bzQAFSscMNkBJxbH7KfaVGgCZAo5gIin0SQeBmLRvRzdIstSwZDZD'
@app.route("/", methods=["GET"])
def root():
return "Hello World!"
# webhook for facebook to initialize the bot
@app.route('/webhook', methods=['GET'])
def get_webhook():
if not 'hub.verify_token' in request.args or not 'hub.challenge' in request.args:
abort(400)
return request.args.get('hub.challenge')
@app.route('/webhook', methods=['POST'])
def post_webhook():
data = request.json
if data["object"] == "page":
for entry in data['entry']:
for messaging_event in entry['messaging']:
if "message" in messaging_event:
sender_id = messaging_event['sender']['id']
if 'text' in messaging_event['message']:
message_text = messaging_event['message']['text']
reply(sender_id, message_text)
return "ok", 200
def reply(recipient_id, message_text):
params = {
"access_token": access_token
}
headers = {
"Content-Type": "application/json"
}
data = json.dumps({
"recipient": {
"id": recipient_id
},
"message": {
"text": message_text
}
})
print data
url = "https://graph.facebook.com/v2.6/me/messages?" + urllib.urlencode(params)
r = urlfetch.fetch(url=url, headers=headers, method='POST', payload=data)