File size: 4,846 Bytes
af3518b
 
 
 
 
 
 
 
 
 
 
 
 
2f5f4e9
af3518b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import os
import threading
import requests
from flask import Flask, request, jsonify

from llm import generate_llm
from sd import generate_sd

GREEN_API_URL = os.getenv("GREEN_API_URL")
GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.com")
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
PORT = 7860

if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE, WEBHOOK_AUTH_TOKEN]):
    raise ValueError("Environment variables are not set properly")

app = Flask(__name__)

def send_message(message_id, to_number, message, retries=3):
    """
    Send a text message using Green API with retry logic.
    """
    if to_number.endswith('@g.us'):
        chat_id = to_number
    else:
        chat_id = to_number

    url = f"{GREEN_API_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMessage/{GREEN_API_TOKEN}"
    payload = {
        "chatId": chat_id,
        "message": message,
        "quotedMessageId": message_id,
    }

    for attempt in range(retries):
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            if attempt < retries - 1:
                continue
            return {"error": str(e)}

def send_image(message_id, to_number, image_path, retries=3):
    """
    Send an image using Green API with retry logic.
    """
    if to_number.endswith('@g.us'):
        chat_id = to_number
    else:
        chat_id = to_number

    url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
    payload = {'chatId': chat_id, 'caption': 'Here you go!', 'quotedMessageId': message_id}
    files = [('file', ('image.jpg', open(image_path, 'rb'), 'image/jpeg'))]

    for attempt in range(retries):
        try:
            response = requests.post(url, data=payload, files=files)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            if attempt < retries - 1:
                continue
            return {"error": str(e)}

def response_text(message_id, chat_id, prompt):
    """
    Generate a response using the LLM and send it to the user.
    """
    try:
        msg = generate_llm(prompt)
        send_message(message_id, chat_id, msg)
    except Exception as e:
        send_message(message_id, chat_id, "There was an error processing your request.")

def handle_image_generation(message_id, chat_id, prompt):
    """
    Generate an image from the provided prompt and send it to the user.
    """
    try:
        image_data, image_path = generate_sd(prompt)
        if image_data:
            send_image(message_id, chat_id, image_path)
        else:
            send_message(message_id, chat_id, "Failed to generate image. Please try again later.")
    except Exception as e:
        send_message(message_id, chat_id, "There was an error generating the image. Please try again later.")

@app.route('/', methods=['GET'])
def index():
    """
    Basic endpoint to check if the script is running.
    """
    return "Server is running!"

@app.route('/whatsapp', methods=['POST'])
def whatsapp_webhook():
    """
    Handle incoming WhatsApp messages.
    """
    data = request.get_json()
    auth_header = request.headers.get('Authorization', '').strip()

    if auth_header != f"Bearer {WEBHOOK_AUTH_TOKEN}":
        return jsonify({"error": "Unauthorized"}), 403

    if data.get('typeWebhook') != 'incomingMessageReceived':
        return jsonify(success=True)

    try:
        chat_id = data['senderData']['chatId']
        message_id = data['idMessage']
        message_data = data.get('messageData', {})

        if 'textMessageData' in message_data:
            body = message_data['textMessageData']['textMessage'].strip()
        elif 'extendedTextMessageData' in message_data:
            body = message_data['extendedTextMessageData']['text'].strip()
        else:
            return jsonify(success=True)

    except KeyError as e:
        return jsonify({"error": f"Missing key in data: {e}"}), 200

    if body.lower().startswith('/imagine'):
        prompt = body.replace('/imagine', '').strip()
        if not prompt:
            send_message(message_id, chat_id, "Please provide a prompt after /imagine.")
        else:
            send_message(message_id, chat_id, "Generating...")
            threading.Thread(target=handle_image_generation, args=(message_id, chat_id, prompt)).start()
    else:
        threading.Thread(target=response_text, args=(message_id, chat_id, body)).start()

    return jsonify(success=True)

if __name__ == '__main__':
    app.run(debug=True, port=PORT, host="0.0.0.0")