Created
July 14, 2018 15:41
-
-
Save elseagle/d61c68de60bb0e32e96d0e8b5a6f4bae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request | |
import json | |
import requests | |
import sys | |
import os | |
import apiai | |
app = Flask(__name__) | |
#Page Access Token | |
PAT = "EAAD8qQHGRvoBACrj5s81oj1ZAZCYXaPHEYOnQ3eoUemTa8X6f8iMAUz3jtOMgaiIzSQrMJr9sxcRxZAF1ZAGUeQSrqKrpqIWAiIL12XIGixCPUOhIIRigfuEz1XgGW3tdjv8LpNVc5UFgUdoew81kJyrPHdclPbcmDy2kiaSIQZDZD" | |
CLIENT_ACCESS_TOKEN = '6998ba1f9216442bb9eaf7366ddc74f8' | |
fb_token = "token_key" | |
@app.route('/webhook', methods=['GET']) | |
def handle_verification(): | |
print("Handling Verification.") | |
if request.args.get('hub.verify_token', '') == fb_token: | |
print("Verification successful!") | |
return request.args.get('hub.challenge', '') | |
else: | |
print("Verification failed!") | |
return 'Error, wrong validation token' | |
@app.route('/webhook', methods=['POST']) | |
def handle_messages(): | |
print("Handling Messages") | |
payload = request.get_data() | |
print(payload) | |
for sender, message in messaging_events(payload): | |
print("Incoming from %s: %s" % (sender, message)) | |
# send message api ai | |
bot_response = parse_user_message(message) | |
# send response from api ai to facebook | |
send_message(PAT, sender, bot_response) | |
return "ok" | |
def messaging_events(payload): | |
"""Generate tuples of (sender_id, message_text) from the | |
provided payload. | |
""" | |
data = json.loads(payload) | |
messaging_events = data["entry"][0]["messaging"] | |
for event in messaging_events: | |
if "message" in event and "text" in event["message"]: | |
yield event["sender"]["id"], event["message"]["text"].encode('unicode_escape') | |
else: | |
yield event["sender"]["id"], "I can't echo this" | |
def send_message(token, recipient, text): | |
"""Send the message text to recipient with id recipient. | |
""" | |
r = requests.post("https://graph.facebook.com/v2.6/me/messages", | |
params={"access_token": token}, | |
data=json.dumps({ | |
"recipient": {"id": recipient}, | |
"message": {"text": text} | |
}), | |
headers={'Content-type': 'application/json'}) | |
if r.status_code != requests.codes.ok: | |
print(r.text) | |
def parse_user_message(user_text): | |
''' | |
Send the message to API AI which invokes an intent | |
and sends the response accordingly | |
The bot response is appened with quotes data fetched from | |
the Quotes_api | |
''' | |
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) | |
r = ai.text_request() | |
r.query = user_text.decode('utf-8') | |
# r.getresponse() | |
response = json.loads(r.getresponse().read().decode('utf-8')) | |
responseStatus = response['status']['code'] | |
if (responseStatus == 200): | |
print("API AI response", response['result']['fulfillment']['speech']) | |
api_response = response['result'] | |
print(response['result']) | |
try: | |
if api_response['metadata']['intentName'] == "state": | |
except KeyError: | |
pass | |
response = api_response['fulfillment']['speech'] | |
return response | |
for message in messages: | |
send_message(sender_id, message) | |
if __name__ == '__main__': | |
port = int(os.environ.get('PORT', 5000)) | |
app.run(host='0.0.0.0', port=port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment