Spaces:
Sleeping
Sleeping
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_dotenv() | |
app = Flask(__name__) | |
VERIFY_TOKEN = os.getenv('VERIFY_TOKEN') | |
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: | |
print('WEBHOOK_VERIFIED') | |
return challenge, 200 | |
else: | |
return 'Forbidden', 403 | |
def handle_messages(): | |
body = request.get_json() | |
if not body.get('entry') or not body['entry'][0].get('messaging'): | |
print('Invalid payload structure:', body) | |
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: | |
print('Missing sender ID or message text:', {'sender_id': sender_id, 'message_text': message_text}) | |
return 'Invalid message', 400 | |
set_typing_on(sender_id) | |
result = chat_completion(message_text) | |
print('Chat Completion Result:', result) | |
response_text = result.get('response', '') | |
try: | |
parsed_response = eval(response_text) # Caution: using eval() is dangerous, ensure the content is trusted | |
except: | |
parsed_response = response_text | |
if isinstance(parsed_response, dict): | |
msg = parsed_response.get('msg') | |
image_url = parsed_response.get('image_url') | |
send_message(sender_id, msg, image_url) | |
else: | |
send_message(sender_id, response_text) | |
set_typing_off(sender_id) | |
print(f'Message sent to {sender_id}: {parsed_response}') | |
return 'OK', 200 | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port=7860, debug=True) | |