Spaces:
Sleeping
Sleeping
from flask import Flask, request | |
import requests | |
import json | |
import os | |
import uuid | |
from db import fetch_json_from_github # Import the GitHub JSON fetcher | |
from qwen import get_qwen_response # Import the Qwen response function | |
from upload import upload_image_to_cdn # Import the new upload function | |
app = Flask(__name__) | |
# Fetch page credentials from GitHub on startup | |
try: | |
github_response = fetch_json_from_github() | |
if github_response["success"]: | |
PAGE_CREDENTIALS = {page['page_id']: page['page_token'] for page in github_response["data"]["pages"]} | |
print("Successfully loaded page credentials from GitHub.") | |
else: | |
print(f"Error loading page credentials: {github_response['message']}") | |
PAGE_CREDENTIALS = {} | |
except Exception as e: | |
print(f"Unexpected error while fetching credentials: {e}") | |
PAGE_CREDENTIALS = {} | |
AI_SERVICE_URL = "https://aoamrnuwara.pythonanywhere.com/send-message" | |
AI_SERVICE_TOKEN = "123400" | |
# Qwen CDN Upload Configuration | |
BASE_URL = "https://chat.qwen.ai" | |
AUTH_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRjOGQyYzY4LWZjNmEtNDEwYy05NWZjLWQ5MDBmNTM4ZTMwMiIsImV4cCI6MTc0NjM1OTExMH0.ms8Agbit2ObnTMJyeW_dUbk-tV_ON_dc-RjDKCDLAwA" | |
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 == AI_SERVICE_TOKEN: | |
return challenge | |
else: | |
return "Verification failed", 403 | |
def handle_message(): | |
body = request.get_json() | |
for entry in body["entry"]: | |
page_id = entry["id"] # Extract page_id from the incoming message | |
page_token = PAGE_CREDENTIALS.get(page_id) | |
if not page_token: | |
print(f"Page ID {page_id} not found in credentials. Skipping...") | |
continue | |
for messaging_event in entry["messaging"]: | |
if "message" in messaging_event: | |
sender_id = messaging_event["sender"]["id"] | |
message = messaging_event["message"] | |
text_content = message.get("text", "") | |
attachments = message.get("attachments", []) | |
image_cdn_urls = [] | |
# Process image attachments | |
for attachment in attachments: | |
if attachment["type"] == "image": | |
image_url = attachment["payload"]["url"] | |
try: | |
# Download image from Messenger | |
img_response = requests.get(image_url) | |
img_response.raise_for_status() | |
temp_path = f"temp_{uuid.uuid4()}.jpg" | |
with open(temp_path, "wb") as f: | |
f.write(img_response.content) | |
# Upload to Qwen CDN | |
cdn_url = upload_image_to_cdn(BASE_URL, AUTH_TOKEN, temp_path) | |
if cdn_url: | |
image_cdn_urls.append(cdn_url) | |
except Exception as e: | |
print(f"Image processing error: {str(e)}") | |
finally: | |
if os.path.exists(temp_path): | |
os.remove(temp_path) | |
# Build message content for Qwen | |
user_content = [] | |
if text_content: | |
user_content.append({"type": "text", "text": text_content}) | |
for cdn_url in image_cdn_urls: | |
user_content.append({"type": "image", "image": cdn_url}) | |
if user_content: | |
ai_response = get_qwen_response(user_content) | |
# Send response back to user | |
headers = { | |
"Authorization": f"Bearer {AI_SERVICE_TOKEN}", | |
"Content-Type": "application/json" | |
} | |
payload = { | |
"recipient_id": sender_id, | |
"message_text": ai_response, | |
"page_access_token": page_token # Include page-specific token | |
} | |
requests.post(AI_SERVICE_URL, json=payload, headers=headers) | |
return "OK", 200 | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=7860, debug=True) |