-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
71 lines (61 loc) · 2.29 KB
/
main.py
File metadata and controls
71 lines (61 loc) · 2.29 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
from flask import Flask, request
import requests
from bot import *
import json
import logging
import random
logging.basicConfig(filename="info.log", filemode='w', level=logging.DEBUG)
app = Flask(__name__)
robot = Robot(10)
ACCESS_TOKEN = "EAAEUY1nxzTEBAAlfrs3CrXTwUYjwfTA93cAFgBQcfhjHeRCi20t8k31P5jEDMXcmZB8gXYhMkDLSZAateRdNQHO0P55mgcWXbSlW6wKj7TWxO0dYzIPZBET8WChpEgFIVyrFtHnxZA26DWYZBAoud3X9Hgshw62IZCxBE4PrAGHwZCEhcB0eiQK"
VER_CODE = "secret"
stickers = ["^_^", ":)", ";)", ":|", ":/", ":(", ":o", "o_o"]
def reply(user_id, msg):
data = {
"recipient": {"id": user_id},
"message": {"text": msg}
}
resp = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token=" + ACCESS_TOKEN, json=data)
if resp.status_code == requests.codes.ok:
logging.info(resp.content)
else:
logging.error(resp.content)
@app.route('/', methods=['GET'])
def handle_verification():
logging.info("Handle verification")
if request.args["hub.verify_token"] == VER_CODE:
logging.info("Verification successful")
return request.args['hub.challenge']
else:
logging.critical("Verification failed")
return 'Error, wrong validation token.'
@app.route('/', methods=['POST'])
def handle_incoming_messages():
logging.info("Incoming messages...")
data = request.get_data()
for sender, message in handle_data(data):
if sender is None:
logging.error("Empty sender.")
continue
elif message is None:
logging.info("Sticker!")
reply(sender, random.choice(stickers))
continue
try:
logging.info("Bot message")
reply(sender, robot.command(message))
except Exception as e:
logging.error("Unexpected error.")
return "ok"
def handle_data(data):
info = json.loads(data)
if 'entry' not in info or 'messaging' not in info['entry'][0] or 'sender' not in info['entry'][0]['messaging'][0]:
return
messages = info['entry'][0]['messaging']
for event in messages:
if "message" in event and "text" in event["message"]:
yield event["sender"]["id"], event["message"]["text"]
elif "sender" in event:
yield event['sender']["id"], None
if __name__ == '__main__':
app.run(debug=True)