Spaces:
Sleeping
Sleeping
from flask import Flask, request, jsonify | |
import requests | |
from dotenv import load_dotenv | |
import os | |
# Load environment variables from .env file | |
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') | |
# Define the API endpoint for sending messages | |
API_URL = f"https://graph.facebook.com/v13.0/me/messages?access_token={PAGE_ACCESS_TOKEN}" | |
def fbverify(): | |
mode = request.args.get("hub.mode") | |
token = request.args.get("hub.verify_token") | |
challenge = request.args.get("hub.challenge") | |
print(f"Verification request - mode: {mode}, token: {token}, challenge: {challenge}") | |
if mode == "subscribe" and challenge: | |
if token == VERIFY_TOKEN: | |
return challenge, 200 | |
else: | |
return "Verification token mismatch", 403 | |
return "Hello world", 200 | |
def fbwebhook(): | |
data = request.get_json() | |
print("Received data:", data) | |
try: | |
# Extract the message and sender ID from the request | |
messaging_event = data['entry'][0]['messaging'][0] | |
message = messaging_event.get('message', {}) | |
sender_id = messaging_event['sender']['id'] | |
print(f"Sender ID: {sender_id}, Message: {message}") | |
# Check if the received message is "hi" | |
if message.get('text') == "hi": | |
request_body = { | |
"recipient": { | |
"id": sender_id | |
}, | |
"message": { | |
"text": "Hello, world!" | |
} | |
} | |
response = requests.post(API_URL, json=request_body) | |
print(f"Response Status Code: {response.status_code}") | |
print(f"Response Body: {response.text}") | |
return jsonify(response.json()), response.status_code | |
except KeyError as e: | |
print(f"KeyError: {e}") | |
return "Invalid payload structure", 400 | |
except Exception as e: | |
print(f"Exception: {e}") | |
return "Internal Server Error", 500 | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port=7860, debug=True) | |