File size: 32,605 Bytes
af3518b
 
 
df706dd
0e53ecc
48f91fc
7995625
ff069bf
faa3c7c
b9724da
 
 
 
ff069bf
af3518b
7995625
df706dd
 
7995625
ff069bf
 
 
 
 
 
 
 
af3518b
 
 
 
7995625
 
 
 
0e53ecc
b9724da
af3518b
ff069bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e53ecc
 
 
 
7995625
 
 
0e53ecc
7995625
0e53ecc
7995625
0e53ecc
7995625
0e53ecc
 
 
ec3a574
0e53ecc
7995625
162ca3a
 
 
 
 
 
 
 
 
 
 
 
 
af3518b
7995625
ff069bf
7995625
 
af3518b
ec3a574
 
 
af3518b
ff069bf
7995625
af3518b
ff069bf
7995625
ff069bf
4beb4cc
ff069bf
7995625
af3518b
ec3a574
 
 
af3518b
ff069bf
7995625
af3518b
b9724da
7995625
 
cd7a57c
7995625
ff069bf
7995625
cd7a57c
7995625
 
 
cd7a57c
ec3a574
 
 
cd7a57c
ff069bf
7995625
cd7a57c
 
b9724da
ff069bf
b9724da
af3518b
 
 
ff069bf
7995625
af3518b
b9724da
7995625
b9724da
cd7a57c
5e86bf8
ec3a574
 
 
 
b9724da
5e86bf8
b9724da
7995625
 
b9724da
af3518b
 
7995625
 
4beb4cc
 
 
 
 
 
 
 
df706dd
af3518b
7995625
4beb4cc
 
7995625
af3518b
ff069bf
b9724da
 
ff069bf
 
 
7995625
ec3a574
 
b9724da
 
ec3a574
 
7995625
b9724da
f913369
7995625
ff069bf
7995625
ff069bf
7995625
0e53ecc
7995625
 
 
 
 
 
ff069bf
 
7995625
ff069bf
 
ec3a574
 
 
7995625
 
 
 
 
 
 
ff069bf
7995625
 
ff069bf
 
 
 
 
 
 
 
162ca3a
ff069bf
 
 
 
 
162ca3a
7995625
 
ec3a574
 
7995625
 
 
 
 
 
 
 
 
ff069bf
7995625
ff069bf
7995625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07534df
7995625
 
 
 
 
 
 
 
 
 
8ac1fbd
7995625
faa3c7c
7995625
faa3c7c
 
7995625
94856b9
 
 
 
 
162ca3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94856b9
162ca3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a638e3
 
162ca3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed8fee4
 
162ca3a
 
 
 
 
 
 
 
7995625
94856b9
 
8ac1fbd
 
 
 
 
 
 
 
48f91fc
0e53ecc
162ca3a
 
7995625
 
 
 
ff069bf
7995625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff069bf
7995625
 
 
 
 
 
ff069bf
7995625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff069bf
7995625
 
 
 
 
 
 
 
 
 
ff069bf
7995625
 
 
 
 
 
 
 
af3518b
ff069bf
af3518b
ff069bf
48f91fc
 
7995625
 
48f91fc
 
7995625
0e53ecc
ff069bf
7995625
 
 
 
 
 
b9724da
af3518b
7995625
 
 
 
 
162ca3a
 
 
 
 
 
 
 
b9724da
c2d7a4c
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import os
import threading
import requests
import logging
import queue
import re
import json
import time
import random
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse
from FLUX import generate_image
from VoiceReply import generate_voice_reply
from polLLM import generate_llm

# Configure logging
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_STATUS_CHAT      = "[email protected]"  # Chat ID for system messages
image_dir            = "/tmp/images"
audio_dir            = "/tmp/audio"

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

# Queues & in‑memory stores
task_queue   = queue.Queue()
trivia_store = {}   # chat_id β†’ {"question":…, "answer":…}
polls        = {}   # chat_id β†’ {"question":…, "options":[…], "votes":{1:0…}, "voters":{jid:opt}}

app = FastAPI()

# Global inactivity tracker
last_message_time = time.time()

# --- Inactivity Monitor ---
def inactivity_monitor():
    global last_message_time
    while True:
        time.sleep(60)  # check every minute
        if time.time() - last_message_time >= 300:  # 5 minutes inactivity
            if BOT_STATUS_CHAT:
                reminder = "⏰ I haven't heard from you in a while! I'm still here if you need anything."
                send_message("inactivity", BOT_STATUS_CHAT, reminder)
            last_message_time = time.time()

threading.Thread(target=inactivity_monitor, daemon=True).start()

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

threading.Thread(target=worker, daemon=True).start()

# --- send helpers ---
def send_message_to_chat(to_number, message, retries=3):
    chat_id = to_number if to_number.endswith("@g.us") else to_number
    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 requests.RequestException as e:
            if i == retries - 1:
                return {"error": str(e)}

def send_message(message_id, to_number, message, retries=3):
    chat_id = to_number if to_number.endswith("@g.us") else 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 i in range(retries):
        try:
            r = requests.post(url, json=payload)
            r.raise_for_status()
            return r.json()
        except requests.RequestException as e:
            if i == retries - 1:
                return {"error": str(e)}

def send_image(message_id, to_number, image_path, caption="Here you go!", retries=3):
    chat_id = to_number if to_number.endswith("@g.us") else to_number
    url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
    payload = {"chatId": chat_id, "caption": caption, "quotedMessageId": message_id}
    files = [("file", ("image.jpg", open(image_path, "rb"), "image/jpeg"))]
    for i in range(retries):
        try:
            r = requests.post(url, data=payload, files=files)
            r.raise_for_status()
            return r.json()
        except requests.RequestException as e:
            if i == retries - 1:
                return {"error": str(e)}

def send_audio(message_id, to_number, audio_path, retries=3):
    logging.debug("send_audio")
    chat_id = to_number if to_number.endswith("@g.us") else to_number
    if not os.path.exists(audio_path):
        logging.debug(f"Missing audio: {audio_path}")
    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}
    try:
        with open(audio_path, "rb") as f:
            files = [("file", ("audio.mp3", f, "audio/mpeg"))]
            for i in range(retries):
                try:
                    r = requests.post(url, data=payload, files=files)
                    r.raise_for_status()
                    return r.json()
                except requests.RequestException as e:
                    if i == retries - 1:
                        return {"error": str(e)}
    except Exception as e:
        return {"error": str(e)}

# --- core response functions ---
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, "Error processing your request.")

def response_audio(message_id, chat_id, prompt):
    logging.debug("response_audio prompt=%s", 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)
            if os.path.exists(audio_path):
                os.remove(audio_path)
        else:
            response_text(message_id, chat_id, prompt)
    except Exception as e:
        logging.debug("audio error: %s", e)
        send_message(message_id, chat_id, "Error generating audio. Try again later.")

def handle_image_generation(message_id, chat_id, prompt):
    try:
        img, path, ret_prompt, url = generate_image(prompt, message_id, message_id, image_dir)
        if img:
            formatted_ret_prompt = "\n\n".join(
                f"_{paragraph.strip()}_" for paragraph in ret_prompt.split("\n\n") if paragraph.strip()
            )
            send_image(
                message_id,
                chat_id,
                path,
                caption=f"✨ Image ready: {url}\n>{chr(8203)} {formatted_ret_prompt}"
            )
        else:
            send_message(message_id, chat_id, "Image generation failed.")
    except Exception as e:
        logging.error("Error in handle_image_generation: %s", e)
        send_message(message_id, chat_id, "Error generating image.")

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

    auth = request.headers.get("Authorization", "").strip()
    if auth != f"Bearer {WEBHOOK_AUTH_TOKEN}":
        raise HTTPException(403, "Unauthorized")
    try:
        data = await request.json()
    except:
        return JSONResponse({"error": "Invalid JSON"}, status_code=400)
    if data.get("typeWebhook") != "incomingMessageReceived":
        return {"success": True}

    logging.debug("recv: %s", data)
    sd = data["senderData"]
    chat = sd["chatId"]
    mid = data["idMessage"]
    sender_jid = sd.get("sender")

    md = data.get("messageData", {})
    if md.get("typeMessage") == "quotedMessage" or "quotedMessage" in md:
        logging.debug("skip native quotedMessage")
        return {"success": True}

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

    if ctx.get("mentionedJid") or ctx.get("mentionedJidList"):
        return {"success": True}
    if chat.endswith("@g.us") and re.search(r"@\d+", body):
        return {"success": True}

    low = body.lower()

    # --- New Commands ---
    if low == "/help":
        help_text = (
            "πŸ€– *Hi there, I'm Eve!* Here are the commands you can use:\n\n"
            "β€’ `/help` – Show this help message.\n"
            "β€’ `/summarize <text>` – Get a quick summary of your text.\n"
            "β€’ `/translate <language>|<text>` – Translate text to your chosen language.\n"
            "β€’ `/joke` – Enjoy a random, funny joke.\n"
            "β€’ `/weather <location>` – Get the current weather for a location.\n"
            "β€’ `/inspire` – Receive a short inspirational quote.\n"
            "β€’ `/trivia` – Start a new trivia question.\n"
            "β€’ `/answer` – Reveal the trivia answer.\n"
            "β€’ `/meme <text>` – Generate a fun meme image.\n"
            "β€’ `/poll <Question>|<Option1>|<Option2>|…` – Create a poll.\n"
            "β€’ `/results` – See current poll results.\n"
            "β€’ `/endpoll` – End the poll and show final results.\n"
            "β€’ `/imagine <prompt>` – Generate an image from your prompt.\n\n"
            "Send any other text and I'll reply with a voice message. I'm here to help, so don't hesitate to ask!"
        )
        send_message(mid, chat, help_text)
        return {"success": True}

    if low.startswith("/summarize "):
        txt = body[len("/summarize "):].strip()
        summary = generate_llm(f"Summarize this text in one short paragraph:\n\n{txt}")
        send_message(mid, chat, summary)
        return {"success": True}

    if low.startswith("/translate "):
        part = body[len("/translate "):]
        if "|" not in part:
            send_message(mid, chat, "Please use `/translate <language>|<text>`")
        else:
            lang, txt = part.split("|", 1)
            resp = generate_llm(f"Translate the following into {lang.strip()}:\n\n{txt.strip()}")
            send_message(mid, chat, resp)
        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, f"{joke['setup']}\n\n{joke['punchline']}")
        except:
            send_message(mid, chat, generate_llm("Tell me a short, funny 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, w)
        except:
            send_message(mid, chat, "Could not fetch weather.")
        return {"success": True}

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

    # TRIVIA
    if low == "/trivia":
        randomSeed = random.randint(0, 999999)
        raw = generate_llm(
        (f"Generate a trivia question and answer depening on this randowm seed {randomSeed} in JSON format like this: "
        "{\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"}")
        )
        def extract_json(text):
            import re
            match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
            if match:
                return match.group(1)
            return text
        try:
            json_text = extract_json(raw)
            obj = json.loads(json_text)
            if "question" in obj and "answer" in obj:
                trivia_store[chat] = obj
                send_message(mid, chat, f"❓ {obj['question']}\nReply with `/answer` to see the answer.")
            else:
                raise ValueError("Missing expected keys.")
        except Exception as e:
            logging.error("Trivia JSON parse error: %s, raw response: %s", e, raw)
            send_message(mid, chat, "Failed to generate trivia. Please try again.")
        return {"success": True}

    # ANSWER: Accept any message starting with /answer
    if low.startswith("/answer"):
        if chat in trivia_store:
            ans = trivia_store.pop(chat)["answer"]
            send_message(mid, chat, f"πŸ’‘ Answer: {ans}")
        else:
            send_message(mid, chat, "No active trivia. Send `/trivia` to start one.")
        return {"success": True}

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

    if low.startswith("/poll "):
        parts = body[len("/poll "):].split("|")
        if len(parts) < 3:
            send_message(mid, chat, "Please use `/poll Question|Option1|Option2|...`")
        else:
            q = parts[0].strip()
            opts = [p.strip() for p in parts[1:]]
            votes = {i+1: 0 for i in range(len(opts))}
            polls[chat] = {"question": q, "options": opts, "votes": votes, "voters": {}}
            txt = f"πŸ“Š *Poll:* {q}\n" + "\n".join(
                f"{i+1}. {opt}" for i, opt in enumerate(opts)
            ) + "\n\nReply with the *option number* to vote."
            send_message(mid, chat, txt)
        return {"success": True}

    if chat in polls and body.isdigit():
        n = int(body)
        p = polls[chat]
        if 1 <= n <= len(p["options"]):
            prev = p["voters"].get(sender_jid)
            if prev:
                p["votes"][prev] -= 1
            p["votes"][n] += 1
            p["voters"][sender_jid] = n
            send_message(mid, chat, f"βœ… Vote recorded: {p['options'][n-1]}")
        return {"success": True}

    if low == "/results":
        if chat in polls:
            p = polls[chat]
            txt = f"πŸ“Š *Results:* {p['question']}\n" + "\n".join(
                f"{i}. {opt}: {p['votes'][i]}" for i, opt in enumerate([""] + p["options"]) if i > 0
            )
            send_message(mid, chat, txt)
        else:
            send_message(mid, chat, "No active poll.")
        return {"success": True}

    if low == "/endpoll":
        if chat in polls:
            p = polls.pop(chat)
            txt = f"πŸ“Š *Final Results:* {p['question']}\n" + "\n".join(
                f"{i}. {opt}: {p['votes'][i]}" for i, opt in enumerate([""] + p["options"]) if i > 0
            )
            send_message(mid, chat, txt)
        else:
            send_message(mid, chat, "No active poll.")
        return {"success": True}

    if low.startswith("/imagine"):
        prompt = body[len("/imagine"):].strip()
        if not prompt:
            send_message(mid, chat, "Please use `/imagine <prompt>` to generate an image.")
        else:
            send_message(mid, chat, "✨ Your image is being generated. Please wait...")
            task_queue.put({
                "type": "image",
                "message_id": mid,
                "chat_id": chat,
                "prompt": prompt
            })
        return {"success": True}

    # Fallback: voice reply for any other text
    task_queue.put({
        "type": "audio",
        "message_id": mid,
        "chat_id": chat,
        "prompt": body
    })
    return {"success": True}

@app.get("/", response_class=PlainTextResponse)
def index():
    return "Server is running!"

if __name__ == "__main__":
    # Send startup message on launch
    def send_startup_message():
        if BOT_STATUS_CHAT:
            startup_msg = "🌟 Hi! I'm Eve, your friendly AI assistant. I'm now live and ready to help with images, voice replies, and more!"
            send_message("startup", BOT_STATUS_CHAT, startup_msg)
        else:
            logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
    send_startup_message()
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)
import os
import threading
import requests
import logging
import queue
import re
import json
import time
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse
from FLUX import generate_image
from VoiceReply import generate_voice_reply
from polLLM import generate_llm

# Configure logging
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_STATUS_CHAT      = "[email protected]"  # Chat ID for system messages
image_dir            = "/tmp/images"
audio_dir            = "/tmp/audio"

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

# Queues & in‑memory stores
task_queue   = queue.Queue()
trivia_store = {}   # chat_id β†’ {"question":…, "answer":…}
polls        = {}   # chat_id β†’ {"question":…, "options":[…], "votes":{1:0…}, "voters":{jid:opt}}

app = FastAPI()

# Global inactivity tracker
last_message_time = time.time()

# --- Inactivity Monitor ---
def inactivity_monitor():
    global last_message_time
    while True:
        time.sleep(60)  # check every minute
        if time.time() - last_message_time >= 300:  # 5 minutes inactivity
            if BOT_STATUS_CHAT:
                reminder = "⏰ I haven't heard from you in a while! I'm still here if you need anything."
                send_message("inactivity", BOT_STATUS_CHAT, reminder)
            last_message_time = time.time()

threading.Thread(target=inactivity_monitor, daemon=True).start()

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

threading.Thread(target=worker, daemon=True).start()

# --- send helpers ---
def send_message(message_id, to_number, message, retries=3):
    chat_id = to_number if to_number.endswith("@g.us") else 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 i in range(retries):
        try:
            r = requests.post(url, json=payload)
            r.raise_for_status()
            return r.json()
        except requests.RequestException as e:
            if i == retries - 1:
                return {"error": str(e)}

def send_image(message_id, to_number, image_path, caption="Here you go!", retries=3):
    chat_id = to_number if to_number.endswith("@g.us") else to_number
    url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
    payload = {"chatId": chat_id, "caption": caption, "quotedMessageId": message_id}
    files = [("file", ("image.jpg", open(image_path, "rb"), "image/jpeg"))]
    for i in range(retries):
        try:
            r = requests.post(url, data=payload, files=files)
            r.raise_for_status()
            return r.json()
        except requests.RequestException as e:
            if i == retries - 1:
                return {"error": str(e)}

def send_audio(message_id, to_number, audio_path, retries=3):
    logging.debug("send_audio")
    chat_id = to_number if to_number.endswith("@g.us") else to_number
    if not os.path.exists(audio_path):
        logging.debug(f"Missing audio: {audio_path}")
    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}
    try:
        with open(audio_path, "rb") as f:
            files = [("file", ("audio.mp3", f, "audio/mpeg"))]
            for i in range(retries):
                try:
                    r = requests.post(url, data=payload, files=files)
                    r.raise_for_status()
                    return r.json()
                except requests.RequestException as e:
                    if i == retries - 1:
                        return {"error": str(e)}
    except Exception as e:
        return {"error": str(e)}

# --- core response functions ---
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, "Error processing your request.")

def response_audio(message_id, chat_id, prompt):
    logging.debug("response_audio prompt=%s", 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)
            if os.path.exists(audio_path):
                os.remove(audio_path)
        else:
            response_text(message_id, chat_id, prompt)
    except Exception as e:
        logging.debug("audio error: %s", e)
        send_message(message_id, chat_id, "Error generating audio. Try again later.")

def handle_image_generation(message_id, chat_id, prompt):
    try:
        img, path, ret_prompt, url = generate_image(prompt, message_id, message_id, image_dir)
        if img:
            formatted_ret_prompt = "\n\n".join(
                f"_{paragraph.strip()}_" for paragraph in ret_prompt.split("\n\n") if paragraph.strip()
            )
            send_image(
                message_id,
                chat_id,
                path,
                caption=f"✨ Image ready: {url}\n>{chr(8203)} {formatted_ret_prompt}"
            )
        else:
            send_message(message_id, chat_id, "Image generation failed.")
    except Exception as e:
        logging.error("Error in handle_image_generation: %s", e)
        send_message(message_id, chat_id, "Error generating image.")

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

    auth = request.headers.get("Authorization", "").strip()
    if auth != f"Bearer {WEBHOOK_AUTH_TOKEN}":
        raise HTTPException(403, "Unauthorized")
    try:
        data = await request.json()
        chat_id = data["senderData"]["chatId"]
        print(f"New message from chat ID: {chat_id}")
    except:
        return JSONResponse({"error": "Invalid JSON"}, status_code=400)
    if data.get("typeWebhook") != "incomingMessageReceived":
        return {"success": True}

    logging.debug("recv: %s", data)
    sd = data["senderData"]
    chat = sd["chatId"]
    mid = data["idMessage"]
    sender_jid = sd.get("sender")

    md = data.get("messageData", {})
    if md.get("typeMessage") == "quotedMessage" or "quotedMessage" in md:
        logging.debug("skip native quotedMessage")
        return {"success": True}

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

    if ctx.get("mentionedJid") or ctx.get("mentionedJidList"):
        return {"success": True}
    if chat.endswith("@g.us") and re.search(r"@\d+", body):
        return {"success": True}

    low = body.lower()

    # --- New Commands ---
    if low == "/help":
        help_text = (
            "πŸ€– *Hi there, I'm Eve!* Here are the commands you can use:\n\n"
            "β€’ `/help` – Show this help message.\n"
            "β€’ `/summarize <text>` – Get a quick summary of your text.\n"
            "β€’ `/translate <language>|<text>` – Translate text to your chosen language.\n"
            "β€’ `/joke` – Enjoy a random, funny joke.\n"
            "β€’ `/weather <location>` – Get the current weather for a location.\n"
            "β€’ `/inspire` – Receive a short inspirational quote.\n"
            "β€’ `/trivia` – Start a new trivia question.\n"
            "β€’ `/answer` – Reveal the trivia answer.\n"
            "β€’ `/meme <text>` – Generate a fun meme image.\n"
            "β€’ `/poll <Question>|<Option1>|<Option2>|…` – Create a poll.\n"
            "β€’ `/results` – See current poll results.\n"
            "β€’ `/endpoll` – End the poll and show final results.\n"
            "β€’ `/imagine <prompt>` – Generate an image from your prompt.\n\n"
            "Send any other text and I'll reply with a voice message. I'm here to help, so don't hesitate to ask!"
        )
        send_message(mid, chat, help_text)
        return {"success": True}

    if low.startswith("/summarize "):
        txt = body[len("/summarize "):].strip()
        summary = generate_llm(f"Summarize this text in one short paragraph:\n\n{txt}")
        send_message(mid, chat, summary)
        return {"success": True}

    if low.startswith("/translate "):
        part = body[len("/translate "):]
        if "|" not in part:
            send_message(mid, chat, "Please use `/translate <language>|<text>`")
        else:
            lang, txt = part.split("|", 1)
            resp = generate_llm(f"Translate the following into {lang.strip()}:\n\n{txt.strip()}")
            send_message(mid, chat, resp)
        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, f"{joke['setup']}\n\n{joke['punchline']}")
        except:
            send_message(mid, chat, generate_llm("Tell me a short, funny 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, w)
        except:
            send_message(mid, chat, "Could not fetch weather.")
        return {"success": True}

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

    # TRIVIA
    if low == "/trivia":
        raw = generate_llm(
            "Generate a unique and random trivia question and answer in JSON format. "
            "The output should strictly follow this example format without extra text:\n\n"
            "{\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"}"
        )
        def extract_json(text):
            import re
            match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
            if match:
                return match.group(1)
            return text
        try:
            json_text = extract_json(raw)
            obj = json.loads(json_text)
            if "question" in obj and "answer" in obj:
                trivia_store[chat] = obj
                send_message(mid, chat, f"❓ {obj['question']}\nReply with `/answer` to see the answer.")
            else:
                raise ValueError("Missing expected keys.")
        except Exception as e:
            logging.error("Trivia JSON parse error: %s, raw response: %s", e, raw)
            send_message(mid, chat, "Failed to generate trivia. Please try again.")
        return {"success": True}

    # ANSWER: Accept any message starting with /answer
    if low.startswith("/answer"):
        if chat in trivia_store:
            ans = trivia_store.pop(chat)["answer"]
            send_message(mid, chat, f"πŸ’‘ Answer: {ans}")
        else:
            send_message(mid, chat, "No active trivia. Send `/trivia` to start one.")
        return {"success": True}

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

    if low.startswith("/poll "):
        parts = body[len("/poll "):].split("|")
        if len(parts) < 3:
            send_message(mid, chat, "Please use `/poll Question|Option1|Option2|...`")
        else:
            q = parts[0].strip()
            opts = [p.strip() for p in parts[1:]]
            votes = {i+1: 0 for i in range(len(opts))}
            polls[chat] = {"question": q, "options": opts, "votes": votes, "voters": {}}
            txt = f"πŸ“Š *Poll:* {q}\n" + "\n".join(
                f"{i+1}. {opt}" for i, opt in enumerate(opts)
            ) + "\n\nReply with the *option number* to vote."
            send_message(mid, chat, txt)
        return {"success": True}

    if chat in polls and body.isdigit():
        n = int(body)
        p = polls[chat]
        if 1 <= n <= len(p["options"]):
            prev = p["voters"].get(sender_jid)
            if prev:
                p["votes"][prev] -= 1
            p["votes"][n] += 1
            p["voters"][sender_jid] = n
            send_message(mid, chat, f"βœ… Vote recorded: {p['options'][n-1]}")
        return {"success": True}

    if low == "/results":
        if chat in polls:
            p = polls[chat]
            txt = f"πŸ“Š *Results:* {p['question']}\n" + "\n".join(
                f"{i}. {opt}: {p['votes'][i]}" for i, opt in enumerate([""] + p["options"]) if i > 0
            )
            send_message(mid, chat, txt)
        else:
            send_message(mid, chat, "No active poll.")
        return {"success": True}

    if low == "/endpoll":
        if chat in polls:
            p = polls.pop(chat)
            txt = f"πŸ“Š *Final Results:* {p['question']}\n" + "\n".join(
                f"{i}. {opt}: {p['votes'][i]}" for i, opt in enumerate([""] + p["options"]) if i > 0
            )
            send_message(mid, chat, txt)
        else:
            send_message(mid, chat, "No active poll.")
        return {"success": True}

    if low.startswith("/imagine"):
        prompt = body[len("/imagine"):].strip()
        if not prompt:
            send_message(mid, chat, "Please use `/imagine <prompt>` to generate an image.")
        else:
            send_message(mid, chat, "✨ Your image is being generated. Please wait...")
            task_queue.put({
                "type": "image",
                "message_id": mid,
                "chat_id": chat,
                "prompt": prompt
            })
        return {"success": True}

    # Fallback: voice reply for any other text
    task_queue.put({
        "type": "audio",
        "message_id": mid,
        "chat_id": chat,
        "prompt": body
    })
    return {"success": True}

@app.get("/", response_class=PlainTextResponse)
def index():
    return "Server is running!"

if __name__ == "__main__":
    # Send startup message on launch
    def send_startup_message():
        if BOT_STATUS_CHAT:
            startup_msg = "🌟 Hi! I'm Eve, your friendly AI assistant. I'm now live and ready to help with images, voice replies, and more!"
            send_message_to_chat(BOT_STATUS_CHAT, startup_msg)
        else:
            logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
    send_startup_message()
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)