masadonline commited on
Commit
f04b063
Β·
verified Β·
1 Parent(s): 4a3942a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -31
app.py CHANGED
@@ -149,36 +149,30 @@ def setup_knowledge_base():
149
  return index, model, chunks
150
 
151
  # --- Monitor Conversations ---
152
- def start_conversation_monitor(client, index, embed_model, text_chunks, specific_sid=None):
153
- monitored_sids = set()
154
 
155
- def poll_conversation(convo_sid):
156
- last_processed_timestamp = None
157
  while True:
158
  try:
159
- latest_msg = fetch_latest_incoming_message(client, convo_sid)
160
- if latest_msg:
161
- msg_time = latest_msg["timestamp"]
162
- if last_processed_timestamp is None or msg_time > last_processed_timestamp:
163
- last_processed_timestamp = msg_time
164
- question = latest_msg["body"]
165
- sender = latest_msg["author"]
166
- print(f"\nπŸ“₯ New message from {sender} in {convo_sid}: {question}")
167
- context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
168
- answer = generate_answer_with_groq(question, context)
169
- send_twilio_message(client, convo_sid, answer)
170
- print(f"πŸ“€ Replied to {sender}: {answer}")
171
- time.sleep(3)
172
  except Exception as e:
173
- print(f"❌ Error in convo {convo_sid} polling:", e)
174
- time.sleep(5)
175
 
176
- def monitor_all_conversations():
177
- if specific_sid:
178
- print(f"➑️ Monitoring only the latest conversation: {specific_sid}")
179
- threading.Thread(target=poll_conversation, args=(specific_sid,), daemon=True).start()
180
 
181
- monitor_all_conversations()
182
 
183
  # --- Streamlit UI ---
184
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
@@ -199,10 +193,6 @@ if all([account_sid, auth_token, GROQ_API_KEY]):
199
  client = Client(account_sid, auth_token)
200
  latest_sid = get_latest_whatsapp_conversation_sid(client)
201
 
202
- if latest_sid:
203
- st.success(f"βœ… Monitoring latest WhatsApp conversation: {latest_sid}")
204
- index, model, chunks = setup_knowledge_base()
205
- threading.Thread(target=start_conversation_monitor, args=(client, index, model, chunks, latest_sid), daemon=True).start()
206
- st.success("🟒 Chatbot is running in background and will reply to the latest conversation.")
207
- else:
208
- st.error("❌ No WhatsApp conversations found.")
 
149
  return index, model, chunks
150
 
151
  # --- Monitor Conversations ---
152
+ def monitor_all_conversations():
153
+ print("➑️ Monitoring all new incoming WhatsApp conversations...")
154
 
155
+ def poll_new_conversations():
156
+ processed_convos = set()
157
  while True:
158
  try:
159
+ conversations = client.conversations.v1.conversations.list(limit=20)
160
+ for convo in conversations:
161
+ if convo.sid not in processed_convos:
162
+ # Check if WhatsApp participant exists
163
+ participants = client.conversations.v1.conversations(convo.sid).participants.list()
164
+ for p in participants:
165
+ address = p.messaging_binding.get("address", "") if p.messaging_binding else ""
166
+ if address.startswith("whatsapp:"):
167
+ processed_convos.add(convo.sid)
168
+ print(f"πŸ†• New conversation detected: {convo.sid}")
169
+ threading.Thread(target=poll_conversation, args=(convo.sid,), daemon=True).start()
 
 
170
  except Exception as e:
171
+ print("❌ Error while polling for new conversations:", e)
172
+ time.sleep(5)
173
 
174
+ threading.Thread(target=poll_new_conversations, daemon=True).start()
 
 
 
175
 
 
176
 
177
  # --- Streamlit UI ---
178
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
 
193
  client = Client(account_sid, auth_token)
194
  latest_sid = get_latest_whatsapp_conversation_sid(client)
195
 
196
+ st.success("🟒 Monitoring new WhatsApp conversations... Waiting for messages.")
197
+ index, model, chunks = setup_knowledge_base()
198
+ threading.Thread(target=start_conversation_monitor, args=(client, index, model, chunks), daemon=True).start()