-
Notifications
You must be signed in to change notification settings - Fork 8
/
app.py
57 lines (48 loc) · 1.85 KB
/
app.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
import os
import requests
from flask import Flask, request
app = Flask(__name__)
FACEBOOK_TOKEN = os.environ["PAGE_ACCESS_TOKEN"]
@app.route('/', methods=['GET'])
def verify():
"""
При верификации вебхука у Facebook он отправит запрос на этот адрес. На него нужно ответить VERIFY_TOKEN.
"""
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():
"""
Основной вебхук, на который будут приходить сообщения от Facebook.
"""
data = request.get_json()
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, message_text)
return "ok", 200
def send_message(recipient_id, message_text):
params = {"access_token": FACEBOOK_TOKEN}
headers = {"Content-Type": "application/json"}
request_content = {
"recipient": {
"id": recipient_id
},
"message": {
"text": message_text
}
}
response = requests.post(
"https://graph.facebook.com/v2.6/me/messages",
params=params, headers=headers, json=request_content
)
response.raise_for_status()
if __name__ == '__main__':
app.run(debug=True)