Spaces:
Paused
Paused
Delete app.py
#2
by
Aymankhal56
- opened
app.py
DELETED
|
@@ -1,226 +0,0 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify
|
| 2 |
-
import requests
|
| 3 |
-
from dotenv import load_dotenv
|
| 4 |
-
import os
|
| 5 |
-
import re
|
| 6 |
-
import json
|
| 7 |
-
from helper.cohere_api import chat_completion # Ensure this import is correct
|
| 8 |
-
|
| 9 |
-
# Load environment variables from .env file
|
| 10 |
-
load_dotenv()
|
| 11 |
-
|
| 12 |
-
app = Flask(__name__)
|
| 13 |
-
|
| 14 |
-
# Retrieve environment variables
|
| 15 |
-
VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
|
| 16 |
-
PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
|
| 17 |
-
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 18 |
-
|
| 19 |
-
# Check if environment variables are set
|
| 20 |
-
if not all([VERIFY_TOKEN, PAGE_ACCESS_TOKEN, OPENAI_API_KEY]):
|
| 21 |
-
raise EnvironmentError("Some environment variables are missing. Please check your .env file.")
|
| 22 |
-
|
| 23 |
-
# Debugging: Print the loaded environment variables (remove in production)
|
| 24 |
-
print(f"VERIFY_TOKEN: {VERIFY_TOKEN}")
|
| 25 |
-
print(f"PAGE_ACCESS_TOKEN: {PAGE_ACCESS_TOKEN}")
|
| 26 |
-
print(f"OPENAI_API_KEY: {OPENAI_API_KEY}")
|
| 27 |
-
|
| 28 |
-
@app.route('/', methods=['GET'])
|
| 29 |
-
def home():
|
| 30 |
-
return "Welcome to the chatbot!"
|
| 31 |
-
|
| 32 |
-
@app.route('/facebook', methods=['GET', 'POST'])
|
| 33 |
-
def webhook():
|
| 34 |
-
if request.method == 'GET':
|
| 35 |
-
# Webhook verification
|
| 36 |
-
verify_token = request.args.get('hub.verify_token')
|
| 37 |
-
challenge = request.args.get('hub.challenge')
|
| 38 |
-
|
| 39 |
-
print(f"GET request received: verify_token={verify_token}, challenge={challenge}")
|
| 40 |
-
|
| 41 |
-
if verify_token == VERIFY_TOKEN:
|
| 42 |
-
print("Verification token matches. Returning challenge.")
|
| 43 |
-
return challenge
|
| 44 |
-
else:
|
| 45 |
-
print("Error: wrong validation token.")
|
| 46 |
-
return 'Error, wrong validation token'
|
| 47 |
-
|
| 48 |
-
elif request.method == 'POST':
|
| 49 |
-
data = request.get_json()
|
| 50 |
-
print(f"POST request received: {data}")
|
| 51 |
-
|
| 52 |
-
if 'entry' in data and len(data['entry']) > 0 and 'messaging' in data['entry'][0]:
|
| 53 |
-
messaging_event = data['entry'][0]['messaging'][0]
|
| 54 |
-
print(f"Messaging event: {messaging_event}")
|
| 55 |
-
|
| 56 |
-
if 'message' in messaging_event:
|
| 57 |
-
# Ignore echo messages
|
| 58 |
-
if messaging_event['message'].get('is_echo'):
|
| 59 |
-
print("Echo message received. Ignoring.")
|
| 60 |
-
return jsonify({'status': 'ok'})
|
| 61 |
-
|
| 62 |
-
sender_id = messaging_event['sender']['id']
|
| 63 |
-
message_text = messaging_event['message'].get('text', '')
|
| 64 |
-
|
| 65 |
-
if not message_text:
|
| 66 |
-
print("Empty message text received. Ignoring.")
|
| 67 |
-
return jsonify({'status': 'ok'})
|
| 68 |
-
|
| 69 |
-
print(f"Received message from {sender_id}: {message_text}")
|
| 70 |
-
|
| 71 |
-
# Set typing on
|
| 72 |
-
set_typing_on(sender_id)
|
| 73 |
-
|
| 74 |
-
try:
|
| 75 |
-
# Get response with possible image URLs
|
| 76 |
-
response_data = chat_completion(message_text, sender_id)
|
| 77 |
-
print("ChatBot Response:\n", response_data)
|
| 78 |
-
response_data = parse_response(response_data)
|
| 79 |
-
print("#"*10)
|
| 80 |
-
print("Parsed Response:\n", response_data)
|
| 81 |
-
print("#"*10)
|
| 82 |
-
response_text = response_data.get('msg', '')
|
| 83 |
-
image_urls = response_data.get('image_urls', [])
|
| 84 |
-
|
| 85 |
-
print(f"ChatBot Response Text: {response_text}")
|
| 86 |
-
print(f"ChatBot Response Image URLs: {image_urls}")
|
| 87 |
-
|
| 88 |
-
# Send text and/or images
|
| 89 |
-
if response_text:
|
| 90 |
-
send_message(sender_id, response_text)
|
| 91 |
-
if image_urls:
|
| 92 |
-
for url in image_urls:
|
| 93 |
-
send_image(sender_id, url)
|
| 94 |
-
|
| 95 |
-
except Exception as e:
|
| 96 |
-
print(f"Exception occurred: {e}")
|
| 97 |
-
send_message(sender_id, "Sorry, something went wrong. Please try again later.")
|
| 98 |
-
|
| 99 |
-
# Mark message as seen
|
| 100 |
-
mark_seen(sender_id)
|
| 101 |
-
# Set typing off after responding
|
| 102 |
-
set_typing_off(sender_id)
|
| 103 |
-
|
| 104 |
-
return jsonify({'status': 'ok'})
|
| 105 |
-
|
| 106 |
-
def parse_response(input_string):
|
| 107 |
-
# Regex pattern to find URLs
|
| 108 |
-
url_pattern = re.compile(r'https?://\S+|www\.\S+')
|
| 109 |
-
urls = re.findall(url_pattern, input_string)
|
| 110 |
-
|
| 111 |
-
# Clean URLs by removing unwanted characters
|
| 112 |
-
cleaned_urls = [re.sub(r'[(){}"\']', '', url) for url in urls]
|
| 113 |
-
|
| 114 |
-
# Extract JSON-like dictionaries from the input string
|
| 115 |
-
json_pattern = re.compile(r'\{.*?\}')
|
| 116 |
-
json_matches = json_pattern.findall(input_string)
|
| 117 |
-
extracted_text = input_string
|
| 118 |
-
|
| 119 |
-
for json_str in json_matches:
|
| 120 |
-
try:
|
| 121 |
-
json_data = json.loads(json_str)
|
| 122 |
-
if isinstance(json_data, dict):
|
| 123 |
-
extracted_text = json_data.get('msg', extracted_text)
|
| 124 |
-
image_urls = json_data.get('image_url', [])
|
| 125 |
-
if isinstance(image_urls, str):
|
| 126 |
-
cleaned_urls.append(re.sub(r'[(){}"\']', '', image_urls))
|
| 127 |
-
elif isinstance(image_urls, list):
|
| 128 |
-
cleaned_urls.extend([re.sub(r'[(){}"\']', '', url) for url in image_urls])
|
| 129 |
-
except json.JSONDecodeError:
|
| 130 |
-
continue
|
| 131 |
-
|
| 132 |
-
# Remove URLs from the extracted text
|
| 133 |
-
text = re.sub(url_pattern, '', extracted_text).strip()
|
| 134 |
-
|
| 135 |
-
# Further clean the text from any leftover JSON artifacts and unwanted parts
|
| 136 |
-
text = re.sub(r'[\)\{\}\[\]\"\(\']', '', text).strip()
|
| 137 |
-
text = re.sub(r'msg:', '', text).strip()
|
| 138 |
-
text = re.sub(r'image_url:', '', text).strip()
|
| 139 |
-
text = text.replace('\n', '').strip()
|
| 140 |
-
text = text.replace(" ", " ")
|
| 141 |
-
|
| 142 |
-
return {
|
| 143 |
-
'msg': text,
|
| 144 |
-
'image_urls': list(set(cleaned_urls))
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
def send_message(recipient_id, message_text):
|
| 148 |
-
url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
|
| 149 |
-
headers = {'Content-Type': 'application/json'}
|
| 150 |
-
payload = {
|
| 151 |
-
'recipient': {'id': recipient_id},
|
| 152 |
-
'message': {'text': message_text}
|
| 153 |
-
}
|
| 154 |
-
print(f"Sending message request: {payload}")
|
| 155 |
-
response = requests.post(url, headers=headers, json=payload)
|
| 156 |
-
print(f"Message send response: {response.status_code}, {response.text}")
|
| 157 |
-
|
| 158 |
-
def send_image(recipient_id, image_url):
|
| 159 |
-
if not verify_image_url(image_url):
|
| 160 |
-
print("Invalid or inaccessible image URL.")
|
| 161 |
-
return
|
| 162 |
-
|
| 163 |
-
url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
|
| 164 |
-
headers = {'Content-Type': 'application/json'}
|
| 165 |
-
payload = {
|
| 166 |
-
'recipient': {'id': recipient_id},
|
| 167 |
-
'message': {
|
| 168 |
-
'attachment': {
|
| 169 |
-
'type': 'image',
|
| 170 |
-
'payload': {
|
| 171 |
-
'url': image_url,
|
| 172 |
-
'is_reusable': True
|
| 173 |
-
}
|
| 174 |
-
}
|
| 175 |
-
}
|
| 176 |
-
}
|
| 177 |
-
print(f"Sending image request: {payload}")
|
| 178 |
-
response = requests.post(url, headers=headers, json=payload)
|
| 179 |
-
print(f"Image send response: {response.status_code}, {response.text}")
|
| 180 |
-
|
| 181 |
-
if response.status_code != 200:
|
| 182 |
-
print(f"Error sending image: {response.json()}")
|
| 183 |
-
|
| 184 |
-
def verify_image_url(image_url):
|
| 185 |
-
try:
|
| 186 |
-
response = requests.head(image_url)
|
| 187 |
-
return response.status_code == 200 and 'image' in response.headers['Content-Type']
|
| 188 |
-
except Exception as e:
|
| 189 |
-
print(f"Error verifying image URL: {e}")
|
| 190 |
-
return False
|
| 191 |
-
|
| 192 |
-
def set_typing_on(recipient_id):
|
| 193 |
-
url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
|
| 194 |
-
headers = {'Content-Type': 'application/json'}
|
| 195 |
-
payload = {
|
| 196 |
-
'recipient': {'id': recipient_id},
|
| 197 |
-
'sender_action': 'typing_on'
|
| 198 |
-
}
|
| 199 |
-
print(f"Sending typing on request: {payload}")
|
| 200 |
-
response = requests.post(url, headers=headers, json=payload)
|
| 201 |
-
print(f"Typing on response: {response.status_code}, {response.text}")
|
| 202 |
-
|
| 203 |
-
def set_typing_off(recipient_id):
|
| 204 |
-
url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
|
| 205 |
-
headers = {'Content-Type': 'application/json'}
|
| 206 |
-
payload = {
|
| 207 |
-
'recipient': {'id': recipient_id},
|
| 208 |
-
'sender_action': 'typing_off'
|
| 209 |
-
}
|
| 210 |
-
print(f"Sending typing off request: {payload}")
|
| 211 |
-
response = requests.post(url, headers=headers, json=payload)
|
| 212 |
-
print(f"Typing off response: {response.status_code}, {response.text}")
|
| 213 |
-
|
| 214 |
-
def mark_seen(recipient_id):
|
| 215 |
-
url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
|
| 216 |
-
headers = {'Content-Type': 'application/json'}
|
| 217 |
-
payload = {
|
| 218 |
-
'recipient': {'id': recipient_id},
|
| 219 |
-
'sender_action': 'mark_seen'
|
| 220 |
-
}
|
| 221 |
-
print(f"Sending mark seen request: {payload}")
|
| 222 |
-
response = requests.post(url, headers=headers, json=payload)
|
| 223 |
-
print(f"Mark seen response: {response.status_code}, {response.text}")
|
| 224 |
-
|
| 225 |
-
if __name__ == '__main__':
|
| 226 |
-
app.run(host="0.0.0.0", port=7860, debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|