File size: 4,575 Bytes
fb34f66
5fa78e9
dee826f
4e8c61d
 
db10a4b
 
 
c55d9c8
fb34f66
 
e916b82
dee826f
e916b82
 
 
 
 
 
 
 
 
dee826f
 
4e6bb7f
e9dbaf1
2f7bbec
d69813f
 
 
4e8c61d
fb34f66
 
 
 
 
 
e9dbaf1
fb34f66
 
 
 
 
 
 
 
 
db10a4b
dee826f
 
 
 
 
 
fb34f66
4e8c61d
fb34f66
4e8c61d
 
 
 
 
 
 
 
 
 
db10a4b
4e8c61d
 
 
 
 
 
 
db10a4b
d69813f
4e8c61d
 
 
 
 
 
 
 
db10a4b
 
 
 
 
 
4e8c61d
db10a4b
4e8c61d
 
 
 
 
 
 
 
 
 
db10a4b
4e8c61d
 
fb34f66
 
 
 
21b29de
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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"

@app.route("/webhook", methods=["GET"])
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

@app.route("/webhook", methods=["POST"])
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)