masadonline commited on
Commit
465fc05
Β·
verified Β·
1 Parent(s): 2caf6dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -29
app.py CHANGED
@@ -90,9 +90,8 @@ def generate_answer_with_groq(question, context):
90
  return response.json()['choices'][0]['message']['content'].strip()
91
 
92
  # --- Twilio Functions ---
93
- def get_whatsapp_conversation_sids(client):
94
- sids = []
95
- conversations = client.conversations.v1.conversations.list(limit=50)
96
  for convo in conversations:
97
  try:
98
  participants = client.conversations.v1.conversations(convo.sid).participants.list()
@@ -100,11 +99,11 @@ def get_whatsapp_conversation_sids(client):
100
  if (p.identity and p.identity.startswith("whatsapp:")) or (
101
  p.messaging_binding and p.messaging_binding.get("address", "").startswith("whatsapp:")
102
  ):
103
- sids.append(convo.sid)
104
- break
105
  except:
106
  continue
107
- return sids
 
108
 
109
  def fetch_latest_incoming_message(client, conversation_sid):
110
  messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
@@ -145,7 +144,7 @@ def setup_knowledge_base():
145
  return index, model, chunks
146
 
147
  # --- Monitor Conversations ---
148
- def start_conversation_monitor(client, index, embed_model, text_chunks):
149
  monitored_sids = set()
150
 
151
  def poll_conversation(convo_sid):
@@ -170,20 +169,10 @@ def start_conversation_monitor(client, index, embed_model, text_chunks):
170
  time.sleep(5)
171
 
172
  def monitor_all_conversations():
173
- while True:
174
- try:
175
- current_sids = set(get_whatsapp_conversation_sids(client))
176
- new_sids = current_sids - monitored_sids
177
- for sid in new_sids:
178
- print(f"➑️ Monitoring new conversation: {sid}")
179
- monitored_sids.add(sid)
180
- threading.Thread(target=poll_conversation, args=(sid,), daemon=True).start()
181
- time.sleep(15)
182
- except Exception as e:
183
- print("❌ Error in conversation monitoring loop:", e)
184
- time.sleep(15)
185
 
186
- threading.Thread(target=monitor_all_conversations, daemon=True).start()
187
 
188
  # --- Streamlit UI ---
189
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
@@ -202,12 +191,16 @@ if not all([account_sid, auth_token, GROQ_API_KEY]):
202
  if all([account_sid, auth_token, GROQ_API_KEY]):
203
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
204
  client = Client(account_sid, auth_token)
205
- conversation_sids = get_whatsapp_conversation_sids(client)
206
-
207
- if conversation_sids:
208
- st.success(f"βœ… {len(conversation_sids)} WhatsApp conversation(s) found. Initializing chatbot...")
209
- index, model, chunks = setup_knowledge_base()
210
- start_conversation_monitor(client, index, model, chunks)
211
- st.success("🟒 Chatbot is running in background and will reply to new messages.")
212
- else:
213
- st.error("❌ No WhatsApp conversations found.")
 
 
 
 
 
90
  return response.json()['choices'][0]['message']['content'].strip()
91
 
92
  # --- Twilio Functions ---
93
+ def get_latest_whatsapp_conversation_sid(client):
94
+ conversations = client.conversations.v1.conversations.list(limit=10, order='desc')
 
95
  for convo in conversations:
96
  try:
97
  participants = client.conversations.v1.conversations(convo.sid).participants.list()
 
99
  if (p.identity and p.identity.startswith("whatsapp:")) or (
100
  p.messaging_binding and p.messaging_binding.get("address", "").startswith("whatsapp:")
101
  ):
102
+ return convo.sid # Only return the latest one
 
103
  except:
104
  continue
105
+ return None
106
+
107
 
108
  def fetch_latest_incoming_message(client, conversation_sid):
109
  messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
 
144
  return index, model, chunks
145
 
146
  # --- Monitor Conversations ---
147
+ def start_conversation_monitor(client, index, embed_model, text_chunks, specific_sid=None):
148
  monitored_sids = set()
149
 
150
  def poll_conversation(convo_sid):
 
169
  time.sleep(5)
170
 
171
  def monitor_all_conversations():
172
+ if specific_sid:
173
+ print(f"➑️ Monitoring only the latest conversation: {specific_sid}")
174
+ threading.Thread(target=poll_conversation, args=(specific_sid,), daemon=True).start()
 
 
 
 
 
 
 
 
 
175
 
 
176
 
177
  # --- Streamlit UI ---
178
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
 
191
  if all([account_sid, auth_token, GROQ_API_KEY]):
192
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
193
  client = Client(account_sid, auth_token)
194
+ latest_sid = get_latest_whatsapp_conversation_sid(client)
195
+
196
+ latest_sid = get_latest_whatsapp_conversation_sid(client)
197
+
198
+ if latest_sid:
199
+ st.success(f"βœ… Monitoring latest WhatsApp conversation: {latest_sid}")
200
+ index, model, chunks = setup_knowledge_base()
201
+ # Start monitoring only this conversation
202
+ threading.Thread(target=start_conversation_monitor, args=(client, index, model, chunks, latest_sid), daemon=True).start()
203
+ st.success("🟒 Chatbot is running in background and will reply to the latest conversation.")
204
+ else:
205
+ st.error("❌ No WhatsApp conversations found.")
206
+