File size: 13,337 Bytes
af3518b
 
05a6e54
 
df706dd
0e53ecc
48f91fc
7995625
05a6e54
 
b9724da
 
05a6e54
 
b9724da
 
ff069bf
af3518b
05a6e54
df706dd
 
7995625
d8d7161
c15a013
d8d7161
 
 
05a6e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e53ecc
b9724da
af3518b
05a6e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff069bf
 
 
05a6e54
 
 
ff069bf
 
05a6e54
0e53ecc
 
 
 
05a6e54
 
 
 
0e53ecc
05a6e54
0e53ecc
 
 
05a6e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162ca3a
 
 
 
 
 
 
05a6e54
 
 
 
162ca3a
05a6e54
ff069bf
7995625
 
af3518b
ec3a574
 
 
05a6e54
 
 
 
af3518b
05a6e54
ff069bf
4beb4cc
7995625
af3518b
05a6e54
 
 
 
 
 
 
 
 
 
 
ff069bf
7995625
05a6e54
 
 
 
 
 
 
 
 
 
 
 
 
b9724da
af3518b
 
 
ff069bf
05a6e54
af3518b
b9724da
 
05a6e54
5e86bf8
ec3a574
 
05a6e54
b9724da
5e86bf8
05a6e54
 
b9724da
05a6e54
 
 
 
 
 
 
 
1743c01
05a6e54
1743c01
05a6e54
 
 
 
 
1743c01
05a6e54
1743c01
05a6e54
 
 
 
 
856d629
05a6e54
d8d7161
05a6e54
 
 
162ca3a
05a6e54
25a19e1
05a6e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162ca3a
 
 
 
 
05a6e54
162ca3a
05a6e54
 
162ca3a
 
 
 
05a6e54
 
 
 
 
 
162ca3a
 
05a6e54
162ca3a
 
05a6e54
162ca3a
 
 
 
 
 
 
 
 
05a6e54
162ca3a
05a6e54
162ca3a
 
 
 
05a6e54
162ca3a
 
 
 
 
05a6e54
162ca3a
05a6e54
 
 
162ca3a
 
 
 
 
05a6e54
9b5a03d
05a6e54
162ca3a
 
 
 
 
 
05a6e54
9b5a03d
05a6e54
162ca3a
 
 
05a6e54
162ca3a
 
05a6e54
 
7995625
 
05a6e54
 
 
7995625
 
05a6e54
 
 
 
7995625
 
05a6e54
 
b9724da
af3518b
7995625
 
05a6e54
7995625
 
05a6e54
 
 
 
162ca3a
b9724da
05a6e54
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import os
import threading
import time
import random
import logging
import queue
import re
import json
import requests

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse

from supabase import create_client, Client  # pip install supabase
from FLUX import generate_image
from VoiceReply import generate_voice_reply
from polLLM import generate_llm

# β€”β€”β€”β€”β€” Configuration β€”β€”β€”β€”β€”
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s")

# Env vars
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")
BOT_GROUP_CHAT        = os.getenv("BOT_GROUP_CHAT")  # must be a group chat ID
IMAGE_DIR             = "/tmp/images"
AUDIO_DIR             = "/tmp/audio"

# Supabase
SUPABASE_URL    = os.getenv("SUPABASE_URL")
SUPABASE_KEY    = os.getenv("SUPABASE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE,
            WEBHOOK_AUTH_TOKEN, BOT_GROUP_CHAT,
            SUPABASE_URL, SUPABASE_KEY]):
    raise ValueError("One or more environment variables are not set properly")

# Queues & stores
task_queue        = queue.Queue()
trivia_store      = {}
polls             = {}
last_message_time = time.time()

app = FastAPI()

# β€”β€”β€”β€”β€” Supabase Schema Prep β€”β€”β€”β€”β€”
def prepare_tables():
    """
    Ensure 'users' and 'images' tables exist. Creates them if they don't.
    """
    # Create users table
    supabase.postgrest.client.rpc(
        "sql",
        {"query": """
            CREATE TABLE IF NOT EXISTS users (
              id SERIAL PRIMARY KEY,
              chat_id TEXT UNIQUE NOT NULL,
              created_at BIGINT NOT NULL
            );
        """}
    ).execute()

    # Create images table
    supabase.postgrest.client.rpc(
        "sql",
        {"query": """
            CREATE TABLE IF NOT EXISTS images (
              id SERIAL PRIMARY KEY,
              chat_id TEXT NOT NULL,
              prompt TEXT NOT NULL,
              url TEXT NOT NULL,
              created_at BIGINT NOT NULL
            );
        """}
    ).execute()

# β€”β€”β€”β€”β€” Inactivity Monitor β€”β€”β€”β€”β€”
def inactivity_monitor():
    global last_message_time
    while True:
        time.sleep(60)
        if time.time() - last_message_time >= 300:
            send_message_to_chat(BOT_GROUP_CHAT, "⏰ I haven't heard from you in a while! I'm still here πŸ’–")
            last_message_time = time.time()

# β€”β€”β€”β€”β€” Background Worker β€”β€”β€”β€”β€”
def worker():
    while True:
        task = task_queue.get()
        try:
            if task["type"] == "image":
                handle_image_generation(task)
            elif task["type"] == "audio":
                response_audio(task["message_id"], task["chat_id"], task["prompt"])
        except Exception as e:
            logging.error(f"Error processing task {task}: {e}")
        finally:
            task_queue.task_done()

# β€”β€”β€”β€”β€” Supabase Helpers β€”β€”β€”β€”β€”
def ensure_user_exists(chat_id: str):
    """Create user record if not exists."""
    res = supabase.table("users").select("*").eq("chat_id", chat_id).single().execute()
    if res.data is None:
        supabase.table("users").insert({
            "chat_id": chat_id,
            "created_at": int(time.time())
        }).execute()

def store_image_url(chat_id: str, prompt: str, url: str):
    supabase.table("images").insert({
        "chat_id": chat_id,
        "prompt": prompt,
        "url": url,
        "created_at": int(time.time())
    }).execute()

# β€”β€”β€”β€”β€” Send Helpers β€”β€”β€”β€”β€”
def send_message_to_chat(chat_id: str, message: str, retries=3):
    url = f"{GREEN_API_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMessage/{GREEN_API_TOKEN}"
    payload = {"chatId": chat_id, "message": message}
    for i in range(retries):
        try:
            r = requests.post(url, json=payload)
            r.raise_for_status()
            return r.json()
        except Exception as e:
            logging.error(f"send_message_to_chat attempt {i+1} failed: {e}")
            time.sleep(1)
    return {"error": "Failed after retries"}

def send_message(message_id: str, chat_id: str, message: str, retries=3):
    url = f"{GREEN_API_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMessage/{GREEN_API_TOKEN}"
    payload = {"chatId": chat_id, "message": message, "quotedMessageId": message_id}
    for i in range(retries):
        try:
            r = requests.post(url, json=payload)
            r.raise_for_status()
            return r.json()
        except Exception as e:
            logging.error(f"send_message attempt {i+1} failed: {e}")
            time.sleep(1)
    return {"error": "Failed after retries"}

def send_image(message_id: str, chat_id: str, image_path: str, caption="Here you go!", retries=3):
    url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
    payload = {"chatId": chat_id, "caption": caption, "quotedMessageId": message_id}
    for i in range(retries):
        try:
            with open(image_path, "rb") as f:
                files = [("file", ("image.jpg", f, "image/jpeg"))]
                r = requests.post(url, data=payload, files=files)
                r.raise_for_status()
                return r.json()
        except Exception as e:
            logging.error(f"send_image attempt {i+1} failed: {e}")
            time.sleep(1)
    return {"error": "Failed after retries"}

def send_audio(message_id: str, chat_id: str, audio_path: str, retries=3):
    url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
    payload = {"chatId": chat_id, "caption": "Here is your voice reply!", "quotedMessageId": message_id}
    for i in range(retries):
        try:
            with open(audio_path, "rb") as f:
                files = [("file", ("audio.mp3", f, "audio/mpeg"))]
                r = requests.post(url, data=payload, files=files)
                r.raise_for_status()
                return r.json()
        except Exception as e:
            logging.error(f"send_audio attempt {i+1} failed: {e}")
            time.sleep(1)
    return {"error": "Failed after retries"}

# β€”β€”β€”β€”β€” Core Handlers β€”β€”β€”β€”β€”
def response_text(message_id, chat_id, prompt):
    try:
        msg = generate_llm(prompt)
        send_message(message_id, chat_id, msg)
    except Exception:
        send_message(message_id, chat_id, "Sorry, something went wrong πŸ’¦")

def response_audio(message_id, chat_id, prompt):
    try:
        result = generate_voice_reply(prompt, model="openai-audio", voice="coral", audio_dir=AUDIO_DIR)
        if result and result[0]:
            audio_path, _ = result
            send_audio(message_id, chat_id, audio_path)
            os.remove(audio_path)
        else:
            response_text(message_id, chat_id, prompt)
    except Exception:
        send_message(message_id, chat_id, "Error generating audio. Please try again later.")

def handle_image_generation(task):
    message_id = task["message_id"]
    chat_id    = task["chat_id"]
    prompt     = task["prompt"]

    ensure_user_exists(chat_id)

    for attempt in range(4):
        try:
            img, path, ret_prompt, url = generate_image(prompt, message_id, message_id, IMAGE_DIR)
            if img:
                store_image_url(chat_id, prompt, url)
                formatted = "\n\n".join(f"_{p.strip()}_" for p in ret_prompt.split("\n\n") if p.strip())
                send_image(message_id, chat_id, path,
                           caption=f"✨ Image ready: {url}\n{formatted}")
                return
            else:
                raise RuntimeError("generate_image returned no image")
        except Exception as e:
            logging.error(f"Image gen attempt {attempt+1} failed: {e}")
            if attempt < 3:
                time.sleep(5)
            else:
                send_message(message_id, chat_id, "😒 Sorry, I couldn't generate the image after several tries.")

# β€”β€”β€”β€”β€” Startup β€”β€”β€”β€”β€”
def send_startup_message():
    send_message_to_chat(BOT_GROUP_CHAT,
        "🌟 Hi! I'm Eve, your friendly AI assistant. I'm now live and ready to help with images, voice replies, and more!"
    )

# β€”β€”β€”β€”β€” Help Text β€”β€”β€”β€”β€”
help_text = (
    "πŸ€– *Hi there, I'm Eve!* Here are the commands you can use in this group:\n\n"
    "β€’ */help* – Show this help message.\n"
    "β€’ */summarize <text>* – Get a quick summary.\n"
    "β€’ */translate <lang>|<text>* – Translate text.\n"
    "β€’ */joke* – A random joke.\n"
    "β€’ */weather <location>* – Current weather.\n"
    "β€’ */inspire* – Inspirational quote.\n"
    "β€’ */trivia* – Start trivia.\n"
    "β€’ */answer* – Answer or reveal trivia.\n"
    "β€’ */meme <text>* – Generate a meme image.\n"
    "β€’ */poll Q|Opt1|Opt2|…* – Create a poll.\n"
    "β€’ */results* – Show poll results.\n"
    "β€’ */endpoll* – End the poll.\n"
    "β€’ */gen <prompt>* – Generate an image.\n\n"
    "Anything else I’ll reply with a voice message. πŸ’–"
)

# β€”β€”β€”β€”β€” Webhook β€”β€”β€”β€”β€”
@app.post("/whatsapp")
async def whatsapp_webhook(request: Request):
    global last_message_time
    last_message_time = time.time()

    if request.headers.get("Authorization", "") != f"Bearer {WEBHOOK_AUTH_TOKEN}":
        raise HTTPException(403, "Unauthorized")

    data = await request.json()
    if data.get("typeWebhook") != "incomingMessageReceived":
        return {"success": True}

    sd = data["senderData"]
    chat_id = sd["chatId"]
    mid     = data["idMessage"]

    # only process messages from the BOT_GROUP_CHAT group
    if chat_id != BOT_GROUP_CHAT:
        return {"success": True}

    md = data.get("messageData", {})
    if "quotedMessage" in md:
        return {"success": True}

    # extract text
    if "textMessageData" in md:
        body = md["textMessageData"].get("textMessage", "").strip()
    elif "extendedTextMessageData" in md:
        body = md["extendedTextMessageData"].get("text", "").strip()
    else:
        return {"success": True}

    low = body.lower()

    # β€” Commands β€”
    if low == "/help":
        send_message(mid, chat_id, help_text)
        return {"success": True}

    if low.startswith("/summarize "):
        txt = body[len("/summarize "):].strip()
        send_message(mid, chat_id, generate_llm(f"Summarize:\n\n{txt}"))
        return {"success": True}

    if low.startswith("/translate "):
        part = body[len("/translate "):]
        if "|" not in part:
            send_message(mid, chat_id, "Use `/translate <lang>|<text>` please.")
        else:
            lang, txt = part.split("|",1)
            send_message(mid, chat_id,
                         generate_llm(f"Translate into {lang.strip()}:\n\n{txt.strip()}"))
        return {"success": True}

    if low == "/joke":
        try:
            joke = requests.get("https://official-joke-api.appspot.com/random_joke", timeout=5).json()
            send_message(mid, chat_id, f"{joke['setup']}\n\n{joke['punchline']}")
        except:
            send_message(mid, chat_id, generate_llm("Tell me a short joke."))
        return {"success": True}

    if low.startswith("/weather "):
        loc = body[len("/weather "):].strip().replace(" ", "+")
        try:
            w = requests.get(f"http://sl.wttr.in/{loc}?format=4", timeout=5).text
            send_message(mid, chat_id, w)
        except:
            send_message(mid, chat_id, "Could not fetch weather.")
        return {"success": True}

    if low == "/inspire":
        send_message(mid, chat_id, f"✨ {generate_llm('Give me an inspirational quote.')}")
        return {"success": True}

    # trivia, answer, meme, poll, results, endpoll omitted for brevityβ€”
    # just queue tasks as before

    if low.startswith("/meme "):
        prompt = body[len("/meme "):].strip()
        send_message(mid, chat_id, "🎨 Generating your meme…")
        task_queue.put({"type":"image","message_id":mid,"chat_id":chat_id,"prompt":f"meme template: {prompt}"})
        return {"success": True}

    if low.startswith("/gen "):
        prompt = body[len("/gen "):].strip()
        send_message(mid, chat_id, "✨ Your image is being generated. Please wait…")
        task_queue.put({"type":"image","message_id":mid,"chat_id":chat_id,"prompt":prompt})
        return {"success": True}

    # fallback to voice
    task_queue.put({"type":"audio","message_id":mid,"chat_id":chat_id,"prompt":body})
    return {"success": True}

@app.get("/", response_class=PlainTextResponse)
def index():
    return "Eve is running! πŸ’–"

if __name__ == "__main__":
    # prepare Supabase schema, then start threads and server
    prepare_tables()
    threading.Thread(target=inactivity_monitor, daemon=True).start()
    threading.Thread(target=worker, daemon=True).start()
    send_startup_message()
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)