File size: 17,485 Bytes
af3518b
 
71b0af4
df706dd
0e53ecc
7995625
71b0af4
 
bd4dd6a
b9724da
6bc0800
b9724da
 
ff069bf
af3518b
bd4dd6a
 
 
1fbbc17
 
 
 
 
 
3ad83d3
1fbbc17
 
 
bd4dd6a
 
 
1fbbc17
 
 
 
 
 
 
 
 
6bc0800
3ad83d3
bd4dd6a
 
 
 
 
3ad83d3
 
bd4dd6a
 
3ad83d3
 
 
bd4dd6a
 
6bc0800
 
 
 
 
 
bd4dd6a
 
 
 
 
 
 
 
 
3ad83d3
 
 
 
 
bd4dd6a
 
3ad83d3
 
 
 
bd4dd6a
3ad83d3
 
bd4dd6a
3ad83d3
 
 
 
 
bd4dd6a
 
 
 
 
 
 
 
 
3ad83d3
df706dd
71b0af4
bd4dd6a
 
05a6e54
0e53ecc
ff069bf
 
 
bd4dd6a
 
6bc0800
 
 
 
ff069bf
 
71b0af4
 
bd4dd6a
0e53ecc
 
 
 
bd4dd6a
3ad83d3
 
 
 
bd4dd6a
3ad83d3
 
 
0e53ecc
3ad83d3
0e53ecc
 
 
bd4dd6a
 
71b0af4
3ad83d3
71b0af4
3ad83d3
 
 
 
 
 
 
af3518b
3ad83d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9724da
3ad83d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9740d0
 
1fbbc17
a9740d0
3ad83d3
 
a9740d0
 
 
 
 
3ad83d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc0800
3ad83d3
 
 
 
 
 
bd4dd6a
 
 
 
25a19e1
3ad83d3
 
 
 
 
 
 
 
 
 
 
 
 
bd4dd6a
71b0af4
162ca3a
 
 
 
 
a9740d0
6bc0800
162ca3a
bd4dd6a
1fbbc17
bd4dd6a
6bc0800
bd4dd6a
162ca3a
3ad83d3
 
 
 
 
 
 
6bc0800
3ad83d3
8f336a6
3ad83d3
 
 
8f336a6
 
1fbbc17
 
8f336a6
3ad83d3
1fbbc17
3ad83d3
 
 
 
 
 
6bc0800
 
3ad83d3
6bc0800
162ca3a
 
 
 
3ad83d3
162ca3a
3ad83d3
162ca3a
3ad83d3
162ca3a
3ad83d3
 
162ca3a
3ad83d3
162ca3a
3ad83d3
6bc0800
3ad83d3
162ca3a
3ad83d3
71b0af4
3ad83d3
71b0af4
3ad83d3
7995625
3ad83d3
71b0af4
3ad83d3
 
bd4dd6a
3ad83d3
 
 
71b0af4
3ad83d3
71b0af4
3ad83d3
71b0af4
3ad83d3
6bc0800
3ad83d3
 
 
 
71b0af4
 
3ad83d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9724da
af3518b
7995625
 
71b0af4
7995625
 
b9724da
b2ef8c6
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
import os
import threading
import requests
import logging
import queue
import json
import time
import random
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import PlainTextResponse
from FLUX import generate_image
from VoiceReply import generate_voice_reply
from polLLM import generate_llm

# --- Configuration and Client Classes ---

class BotConfig:
    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        = "[email protected]"
    BOT_JID               = os.getenv("BOT_JID")    # your bot's own WhatsApp JID
    IMAGE_DIR             = "/tmp/images"
    AUDIO_DIR             = "/tmp/audio"
    DEFAULT_IMAGE_COUNT   = 4

    @classmethod
    def validate(cls):
        missing = [
            name for name in (
                "GREEN_API_URL",
                "GREEN_API_TOKEN",
                "GREEN_API_ID_INSTANCE",
                "WEBHOOK_AUTH_TOKEN",
                "BOT_JID",
            ) if not getattr(cls, name)
        ]
        if missing:
            raise ValueError(f"Missing env vars: {', '.join(missing)}")

class BotClient:
    def __init__(self, cfg: BotConfig):
        self.cfg = cfg
        self.session = requests.Session()
        logging.basicConfig(level=logging.DEBUG,
                            format="%(asctime)s [%(levelname)s] %(message)s")

    def send(self, endpoint: str, payload: dict, files=None, retries=3):
        url = (f"{self.cfg.GREEN_API_URL}/waInstance"
               f"{self.cfg.GREEN_API_ID_INSTANCE}/{endpoint}/"
               f"{self.cfg.GREEN_API_TOKEN}")
        for attempt in range(1, retries + 1):
            try:
                resp = self.session.post(
                    url,
                    json=payload if files is None else None,
                    data=None if files is None else payload,
                    files=files
                )
                resp.raise_for_status()
                return resp.json()
            except requests.RequestException as e:
                logging.warning(f"Attempt {attempt}/{retries} failed for {endpoint}: {e}")
                if attempt == retries:
                    logging.error(f"{endpoint} ultimately failed: {e}")
                    return {"error": str(e)}

    def send_message(self, message_id: str, chat_id: str, text: str):
        return self.send("sendMessage", {
            "chatId": chat_id,
            "message": text,
            "quotedMessageId": message_id
        })

    def send_message_to(self, chat_id: str, text: str):
        return self.send("sendMessage", {
            "chatId": chat_id,
            "message": text
        })

    def send_media(self, message_id: str, chat_id: str, file_path: str,
                   caption: str, media_type: str):
        endpoint = "sendFileByUpload"
        payload = {
            "chatId": chat_id,
            "caption": caption,
            "quotedMessageId": message_id
        }
        with open(file_path, "rb") as f:
            mime = "image/jpeg" if media_type == "image" else "audio/mpeg"
            files = [("file", (os.path.basename(file_path), f, mime))]
            return self.send(endpoint, payload, files=files)

# Validate env
BotConfig.validate()
client = BotClient(BotConfig)

# --- Threading, Queues, Stores ---

task_queue   = queue.Queue()
trivia_store = {}
polls        = {}
last_message_time = time.time()

def inactivity_monitor():
    global last_message_time
    while True:
        time.sleep(60)
        if time.time() - last_message_time >= 300:
            client.send_message_to(
                BotConfig.BOT_GROUP_CHAT,
                "⏰ I haven't heard from you in a while! I'm still here if you need anything."
            )
            last_message_time = time.time()

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

executor = ThreadPoolExecutor(max_workers=4)
def worker():
    while True:
        task = task_queue.get()
        try:
            if task["type"] == "image":
                _fn_generate_images(task["message_id"],
                                    task["chat_id"],
                                    task["prompt"],
                                    task.get("num_images", 1))
            elif task["type"] == "audio":
                _fn_voice_reply(task["message_id"],
                                task["chat_id"],
                                task["prompt"])
        except Exception as e:
            logging.error(f"Worker error {task}: {e}")
        finally:
            task_queue.task_done()

for _ in range(4):
    threading.Thread(target=worker, daemon=True).start()

# --- Primitive “tool” functions ---

def _fn_summarize(message_id, chat_id, text):
    summary = generate_llm(f"Summarize this text in one short paragraph:\n\n{text}")
    client.send_message(message_id, chat_id, summary)

def _fn_translate(message_id, chat_id, lang, text):
    resp = generate_llm(f"Translate the following into {lang}:\n\n{text}")
    client.send_message(message_id, chat_id, resp)

def _fn_joke(message_id, chat_id):
    try:
        j = requests.get("https://official-joke-api.appspot.com/random_joke", timeout=5).json()
        joke = f"{j['setup']}\n\n{j['punchline']}"
    except:
        joke = generate_llm("Tell me a short, funny joke.")
    client.send_message(message_id, chat_id, joke)

def _fn_weather(message_id, chat_id, loc):
    raw = requests.get(f"http://sl.wttr.in/{loc}?format=4", timeout=5).text
    report = generate_llm(
        f"Convert this weather report into Celsius and craft a short, creative report:\n\n{raw}"
    )
    client.send_message(message_id, chat_id, report)
    task_queue.put({
        "type":"audio","message_id":message_id,"chat_id":chat_id,
        "prompt":f"Speak only this weather report: {report}"
    })

def _fn_weather_poem(message_id, chat_id, loc):
    raw = requests.get(f"http://sl.wttr.in/{loc}?format=4", timeout=5).text
    poem = generate_llm(
        f"Write a short, poetic weather summary in Celsius based on:\n\n{raw}"
    )
    client.send_message(message_id, chat_id, poem)
    task_queue.put({
        "type":"audio","message_id":message_id,"chat_id":chat_id,
        "prompt":f"Speak only this poetic weather summary: {poem}"
    })

def _fn_inspire(message_id, chat_id):
    quote = generate_llm(f"Give me a short inspirational unique quote.")
    client.send_message(message_id, chat_id, f"✨ {quote}")

def _fn_trivia(message_id, chat_id):
    raw = generate_llm(
        f"Generate a unique trivia Q&A in JSON: {{\"question\":\"...\",\"answer\":\"...\"}}"
    )
    try:
        obj = json.loads(raw.strip().strip("```json").strip("```"))
        trivia_store[chat_id] = obj
        client.send_message(
            message_id, chat_id,
            f"❓ {obj['question']}\nReply `/answer` or `/answer your guess`."
        )
    except:
        client.send_message(message_id, chat_id, "Failed to generate trivia.")

def _fn_answer(message_id, chat_id, guess):
    if chat_id not in trivia_store:
        client.send_message(message_id, chat_id, "No active trivia. `/trivia` to start.")
        return
    qa = trivia_store.pop(chat_id)
    if guess:
        verdict = generate_llm(
            f"Q: {qa['question']}\nCorrect: {qa['answer']}\nUser: {guess}\nCorrect?"
        )
        client.send_message(message_id, chat_id, verdict)
    else:
        client.send_message(message_id, chat_id, f"💡 Answer: {qa['answer']}")

def _fn_meme(message_id, chat_id, txt):
    client.send_message(message_id, chat_id, "🎨 Generating your meme...")
    task_queue.put({"type":"image","message_id":message_id,
                    "chat_id":chat_id,"prompt":f"meme: {txt}"})

def _fn_poll(message_id, chat_id, question, options):
    votes = {i+1:0 for i in range(len(options))}
    polls[chat_id] = {"question":question,"options":options,"votes":votes,"voters":{}}
    text = f"📊 *Poll:* {question}\n" + "\n".join(
        f"{i+1}. {o}" for i,o in enumerate(options)
    )
    client.send_message(message_id, chat_id, text)

def _fn_poll_vote(message_id, chat_id, voter, choice):
    poll = polls.get(chat_id)
    if not poll or choice < 1 or choice > len(poll["options"]):
        return
    prev = poll["voters"].get(voter)
    if prev:
        poll["votes"][prev] -= 1
    poll["votes"][choice] += 1
    poll["voters"][voter] = choice
    client.send_message(message_id, chat_id,
                        f"✅ Voted for {poll['options'][choice-1]}")

def _fn_poll_results(message_id, chat_id):
    poll = polls.get(chat_id)
    if not poll:
        client.send_message(message_id, chat_id, "No active poll.")
        return
    text = f"📊 *Results:* {poll['question']}\n" + "\n".join(
        f"{i}. {o}: {poll['votes'][i]}" for i,o in enumerate(poll["options"],1)
    )
    client.send_message(message_id, chat_id, text)

def _fn_poll_end(message_id, chat_id):
    poll = polls.pop(chat_id, None)
    if not poll:
        client.send_message(message_id, chat_id, "No active poll.")
        return
    text = f"📊 *Final Results:* {poll['question']}\n" + "\n".join(
        f"{i}. {o}: {poll['votes'][i]}" for i,o in enumerate(poll["options"],1)
    )
    client.send_message(message_id, chat_id, text)

def _fn_generate_images(message_id, chat_id, prompt, count=1):
    for i in range(1, count+1):
        try:
            img, path, ret_prompt, url = generate_image(
                prompt, message_id, message_id, BotConfig.IMAGE_DIR
            )
            formatted = "\n\n".join(f"_{p.strip()}_"
                                    for p in ret_prompt.split("\n\n") if p.strip())
            caption = f"✨ Image {i}/{count}: {url}\n>{chr(8203)} {formatted}"
            client.send_media(message_id, chat_id, path, caption, media_type="image")
            os.remove(path)
        except Exception as e:
            logging.warning(f"Image {i}/{count} failed: {e}")
            client.send_message(message_id, chat_id,
                                f"😢 Failed to generate image {i}/{count}.")

def _fn_voice_reply(message_id, chat_id, prompt):
    result = generate_voice_reply(prompt,
                                  model="openai-audio",
                                  voice="coral",
                                  audio_dir=BotConfig.AUDIO_DIR)
    if result and result[0]:
        audio_path, _ = result
        client.send_media(message_id, chat_id, audio_path, "", media_type="audio")
        os.remove(audio_path)
    else:
        # fallback to text
        response = generate_llm(prompt)
        client.send_message(message_id, chat_id, response)

# --- Intent router for fallback ---

FUNCTION_SCHEMA = {
    "generate_image": {
        "description": "Generate one or more images",
        "params": ["prompt","count"]
    },
    "send_text": {
        "description": "Send a plain text response",
        "params": ["message"]
    }
}

def route_intent(user_input: str):
    """
    Ask the LLM whether to call a function or just chat.
    Expects a JSON response like:
      {"action":"generate_image","prompt":"a sunset","count":2}
      or
      {"action":"send_text","message":"Here's my reply..."}
    """
    sys_prompt = (
        "You are Eve. You can either chat normally or call one of these functions:\n"
        + "\n".join(f"- {name}: {info['description']}"
                    for name,info in FUNCTION_SCHEMA.items())
        + "\n\nIf the user wants an image generated, return JSON with "
          "\"action\":\"generate_image\",\"prompt\":\"...\",\"count\":<int>.\n"
        "Otherwise return JSON with \"action\":\"send_text\",\"message\":\"...\".\n"
        "Do NOT wrap your response in any extra text—only raw JSON."
    )
    raw = generate_llm(f"{sys_prompt}\nUser: {user_input}")
    try:
        return json.loads(raw)
    except:
        # fallback: treat entire raw as chat
        return {"action":"send_text","message":raw}

# --- FastAPI App & Webhook ---

app = FastAPI()
help_text = (
    "🤖 *Hi, I'm Eve!* Commands:\n"
    "• /help\n"
    "• /summarize <text>\n"
    "• /translate <lang>|<text>\n"
    "• /joke\n"
    "• /weather <loc>\n"
    "• /weatherpoem <loc>\n"
    "• /inspire\n"
    "• /trivia / /answer\n"
    "• /meme <text>\n"
    "• /poll <Q>|<opt1>|… / /results / /endpoll\n"
    "• /gen <prompt>|<count>\n"
    "Otherwise I’ll chat or generate images for you!"
)

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

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

    data    = await request.json()
    chat_id = data.get("senderData", {}).get("chatId")
    if chat_id != BotConfig.BOT_GROUP_CHAT or data.get("typeWebhook") != "incomingMessageReceived":
        return {"success": True}

    md   = data["messageData"]
    mid  = data["idMessage"]
    tmd  = md.get("textMessageData") or md.get("extendedTextMessageData")
    if not tmd:
        return {"success": True}
    body = tmd.get("textMessage", tmd.get("text", "")).strip()
    ctx  = tmd.get("contextInfo", {})

    # 1) Quoted‑reply to bot
    if md.get("typeMessage") == "quotedMessage":
        ext = md["extendedTextMessageData"]
        quoted = md["quotedMessage"]
        if ext.get("participant") == BotConfig.BOT_JID:
            user_reply  = ext.get("text", "")
            quoted_text = quoted.get("textMessage", "")
            prompt = (
                f"You asked: {quoted_text}\n"
                f"User replied: {user_reply}\n"
                "Provide a helpful follow‑up."
            )
            ans = generate_llm(prompt)
            client.send_message(mid, chat_id, ans)
            task_queue.put({
                "type":"audio","message_id":mid,
                "chat_id":chat_id,"prompt":ans
            })
        return {"success": True}

    # 2) Mentions skip
    if ctx.get("mentionedJidList"):
        return {"success": True}

    low = body.lower()

    # 3) Slash‑commands
    if low == "/help":
        client.send_message(mid, chat_id, help_text); return {"success": True}
    if low.startswith("/summarize "):
        _fn_summarize(mid, chat_id, body[11:].strip()); return {"success": True}
    if low.startswith("/translate "):
        lang, txt = body[11:].split("|",1)
        _fn_translate(mid, chat_id, lang.strip(), txt.strip()); return {"success": True}
    if low == "/joke":
        _fn_joke(mid, chat_id); return {"success": True}
    if low.startswith("/weather "):
        _fn_weather(mid, chat_id, body[9:].strip().replace(" ","+")); return {"success": True}
    if low.startswith("/weatherpoem "):
        _fn_weather_poem(mid, chat_id, body[13:].strip().replace(" ","+")); return {"success": True}
    if low == "/inspire":
        _fn_inspire(mid, chat_id); return {"success": True}
    if low == "/trivia":
        _fn_trivia(mid, chat_id); return {"success": True}
    if low.startswith("/answer"):
        _fn_answer(mid, chat_id, body[7:].strip()); return {"success": True}
    if low.startswith("/meme "):
        _fn_meme(mid, chat_id, body[6:].strip()); return {"success": True}
    if low.startswith("/poll "):
        parts = [p.strip() for p in body[6:].split("|")]
        _fn_poll(mid, chat_id, parts[0], parts[1:]); return {"success": True}
    if chat_id in polls and low.isdigit():
        _fn_poll_vote(mid, chat_id,
                      data["senderData"]["sender"],
                      int(low)); return {"success": True}
    if low == "/results":
        _fn_poll_results(mid, chat_id); return {"success": True}
    if low == "/endpoll":
        _fn_poll_end(mid, chat_id); return {"success": True}
    if low.startswith("/gen"):
        parts = body[4:].split("|",1)
        prompt = parts[0].strip()
        cnt    = int(parts[1]) if len(parts)>1 and parts[1].isdigit() else BotConfig.DEFAULT_IMAGE_COUNT
        client.send_message(mid, chat_id, f"✨ Generating {cnt} image(s)…")
        task_queue.put({"type":"image","message_id":mid,"chat_id":chat_id,
                        "prompt":prompt,"num_images":cnt})
        return {"success": True}

    # 4) Fallback → function calling router
    intent = route_intent(body)
    act    = intent.get("action")
    if act == "generate_image":
        pr = intent.get("prompt","")
        ct = intent.get("count",1)
        client.send_message(mid, chat_id, f"👍 Generating {ct} images for “{pr}”…")
        task_queue.put({"type":"image","message_id":mid,"chat_id":chat_id,
                        "prompt":pr,"num_images":ct})
    else:
        # send_text or any unknown
        msg = intent.get("message", "Sorry, I didn't understand.")
        client.send_message(mid, chat_id, msg)
        task_queue.put({"type":"audio","message_id":mid,"chat_id":chat_id,
                        "prompt":msg})

    return {"success": True}

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

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)