Spaces:
Sleeping
Sleeping
from flask import Flask, request, jsonify | |
import requests | |
app = Flask(__name__) | |
VERIFY_TOKEN = 'imseldrith' # Replace with your verification token | |
def home(): | |
return "Welcome to the chatbot!" | |
def webhook(): | |
if request.method == 'GET': | |
# Webhook verification | |
verify_token = request.args.get('hub.verify_token') | |
challenge = request.args.get('hub.challenge') | |
print(f"GET request received: verify_token={verify_token}, challenge={challenge}") | |
if verify_token == VERIFY_TOKEN: | |
print("Verification token matches. Returning challenge.") | |
return challenge | |
else: | |
print("Error: wrong validation token.") | |
return 'Error, wrong validation token' | |
elif request.method == 'POST': | |
data = request.get_json() | |
print(f"POST request received: {data}") | |
if 'entry' in data and len(data['entry']) > 0 and 'messaging' in data['entry'][0]: | |
messaging_event = data['entry'][0]['messaging'][0] | |
print(f"Messaging event: {messaging_event}") | |
if 'message' in messaging_event: | |
sender_id = messaging_event['sender']['id'] | |
message_text = messaging_event['message'].get('text', '') | |
print(f"Received message from {sender_id}: {message_text}") | |
if message_text.lower() == 'hi': | |
response_text = 'hello' | |
print(f"Sending response to {sender_id}: {response_text}") | |
send_message(sender_id, response_text) | |
else: | |
print(f"No action taken for message: {message_text}") | |
return jsonify({'status': 'ok'}) | |
def send_message(recipient_id, message_text): | |
access_token = 'YOUR_PAGE_ACCESS_TOKEN' # Replace with your Facebook Page Access Token | |
url = f'https://graph.facebook.com/v12.0/me/messages?access_token={access_token}' | |
headers = {'Content-Type': 'application/json'} | |
payload = { | |
'recipient': {'id': recipient_id}, | |
'message': {'text': message_text} | |
} | |
print(f"Sending message request: {payload}") | |
response = requests.post(url, headers=headers, json=payload) | |
print(f"Message send response: {response.status_code}, {response.text}") | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port=7860, debug=True) | |