Spaces:
Sleeping
Sleeping
File size: 2,263 Bytes
92b3530 9cc7fe7 92b3530 9cc7fe7 92b3530 9cc7fe7 92b3530 37b9f66 3c83fc5 9cc7fe7 37b9f66 92b3530 9cc7fe7 92b3530 9cc7fe7 92b3530 9cc7fe7 92b3530 a29a451 9cc7fe7 92b3530 9cc7fe7 92b3530 9cc7fe7 92b3530 |
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 |
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import os
from helper.openai_api import chat_completion
from helper.messenger_api import send_message, set_typing_on, set_typing_off
# Load environment variables
load_dotenv()
app = Flask(__name__)
# Retrieve environment variables
VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
# Debugging: Print the loaded environment variables
print(f"VERIFY_TOKEN: {VERIFY_TOKEN}")
print(f"PAGE_ACCESS_TOKEN: {PAGE_ACCESS_TOKEN}")
print(f"OPENAI_API_KEY: {OPENAI_API_KEY}")
@app.route('/', methods=['GET'])
def home():
return 'FACEBOOK CHATBOT', 200
@app.route('/facebook', methods=['GET'])
def verify_webhook():
mode = request.args.get('hub.mode')
token = request.args.get('hub.verify_token')
challenge = request.args.get('hub.challenge')
if mode == 'subscribe' and token == VERIFY_TOKEN:
return challenge, 200
else:
return 'Forbidden', 403
@app.route('/webhook', methods=['POST'])
def handle_messages():
body = request.get_json()
print('Incoming request body:', body) # Log the entire request body
if not body.get('entry') or not body['entry'][0].get('messaging'):
return 'Invalid payload', 400
messaging_event = body['entry'][0]['messaging'][0]
sender_id = messaging_event['sender']['id']
message_text = messaging_event['message'].get('text')
if not sender_id or not message_text:
return 'Invalid message', 400
set_typing_on(sender_id)
result = chat_completion(message_text)
response_text = result.get('response', '')
try:
parsed_response = response_text # Caution: using eval() is dangerous, ensure the content is trusted
if not isinstance(parsed_response, dict):
raise ValueError("Response is not a valid dictionary")
except:
parsed_response = {'msg': response_text, 'image_url': None}
msg = parsed_response.get('msg')
image_url = parsed_response.get('image_url')
send_message(sender_id, msg, image_url)
set_typing_off(sender_id)
return 'OK', 200
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860, debug=True)
|