bcci commited on
Commit
5a2f268
·
verified ·
1 Parent(s): 93681af

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import time
3
+ from threading import Thread
4
+ from whatsapp_bridge.bot import ApplicationBuilder, MessageHandler, TypeHandler
5
+ from whatsapp_bridge.bot import TextFilter
6
+ from groq import Groq
7
+ import os
8
+ import uvicorn
9
+ from fastapi import FastAPI
10
+
11
+ # Configure logging
12
+ logging.basicConfig(
13
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
14
+ level=logging.INFO
15
+ )
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Initialize Groq client
19
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
20
+
21
+ # System prompt to define assistant behavior
22
+ system_prompt = """
23
+ You are Lucy, personal assistant of Naksh.
24
+ For the first incoming message reply,
25
+ Hi! I am Lucy, Personal Assistant of Naksh. He is currently busy and will message you soon.
26
+ The second message should be different.
27
+ Every message should be different and also always be respectful.
28
+ you can even chat with the sender
29
+ From the second message you can handle the conversation by yourself
30
+ If someone asks about me tell them he is busy in some work.
31
+ """
32
+
33
+ # Global sender instance
34
+ sender = None
35
+
36
+ class WhatsAppSender:
37
+ def __init__(self, application):
38
+ self.application = application
39
+ self.client = None
40
+
41
+ def get_client(self):
42
+ if self.client is None and hasattr(self.application, 'listener'):
43
+ self.client = self.application.listener.client
44
+ return self.client
45
+
46
+ def send_message(self, jid, message):
47
+ client = self.get_client()
48
+ if client is None:
49
+ return False, "WhatsApp client not available"
50
+ try:
51
+ for method_name in ['send_message', 'send_text', 'send']:
52
+ if hasattr(client, method_name):
53
+ getattr(client, method_name)(jid, message)
54
+ return True, "Message sent successfully"
55
+ return False, "No valid send method found on client"
56
+ except Exception as e:
57
+ return False, str(e)
58
+
59
+ async def ai_handler(update, context):
60
+ global sender
61
+ if not (update.message and update.message.get("content")):
62
+ return
63
+
64
+ chat_jid = update.message.get("chat_jid")
65
+ incoming = update.message.get("content")
66
+ logger.info(f"Received from {chat_jid}: '{incoming}'")
67
+
68
+ messages = [
69
+ {"role": "system", "content": system_prompt},
70
+ {"role": "user", "content": incoming}
71
+ ]
72
+
73
+ try:
74
+ response = client.chat.completions.create(
75
+ messages=messages,
76
+ model="llama-3.3-70b-versatile",
77
+ stream=False,
78
+ )
79
+ ai_text = response.choices[0].message.content
80
+ except Exception as e:
81
+ logger.error(f"Groq AI error: {e}")
82
+ ai_text = "Sorry, I'm having trouble responding right now."
83
+
84
+ success, result = sender.send_message(chat_jid, ai_text)
85
+ if success:
86
+ logger.info(f"Sent to {chat_jid}: '{ai_text}'")
87
+ else:
88
+ logger.error(f"Failed to send message to {chat_jid}: {result}")
89
+
90
+ def cli_send_loop(sender_instance):
91
+ while True:
92
+ try:
93
+ command = input("\nEnter command (/send <jid> <message>): ").strip()
94
+ except EOFError:
95
+ break # no CLI in non-interactive env
96
+
97
+ if command.startswith("/send "):
98
+ parts = command.split(" ", 2)
99
+ if len(parts) < 3:
100
+ print("Invalid format. Use: /send <jid> <message>")
101
+ continue
102
+ _, jid, message = parts
103
+ success, result = sender_instance.send_message(jid, message)
104
+ if success:
105
+ logger.info(f"Message sent to {jid}: '{message}'")
106
+ else:
107
+ logger.error(f"Failed to send: {result}")
108
+ print(f"Error: {result}")
109
+
110
+
111
+ # FastAPI setup
112
+ app = FastAPI()
113
+
114
+ @app.get("/ping")
115
+ async def ping():
116
+ return {"message": "pong"}
117
+
118
+
119
+ def run_fastapi(port=8000):
120
+ uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
121
+
122
+
123
+ def main():
124
+ global sender
125
+ logger.info("Starting WhatsApp AI bot...")
126
+
127
+ application = ApplicationBuilder().build()
128
+ sender = WhatsAppSender(application)
129
+
130
+ application.add_handler(TypeHandler(lambda u, c: logger.debug(f"Update: {u}")), group=-1)
131
+ application.add_handler(MessageHandler(TextFilter(), ai_handler))
132
+
133
+ cli_thread = Thread(target=cli_send_loop, args=(sender,), daemon=True)
134
+ cli_thread.start()
135
+
136
+ # Start FastAPI in a separate thread
137
+ fastapi_thread = Thread(target=run_fastapi, daemon=True)
138
+ fastapi_thread.start()
139
+
140
+ application.run_polling()
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()