VietCat commited on
Commit
d2cbfc0
·
1 Parent(s): 09c294c

fix duplicate message

Browse files
Files changed (1) hide show
  1. app/main.py +37 -51
app/main.py CHANGED
@@ -184,8 +184,32 @@ async def process_message(message_data: Dict[str, Any]):
184
  logger.info("[DUPLICATE] Message duplicate, skipping log.")
185
  return
186
 
187
- # Tìm conversation chưa kết thúc (isdone = false)
188
- open_conv = next((row for row in history if not row.get('isdone')), None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  # Get page access token (sync)
191
  page_token = supabase_client.get_page_token(page_id)
@@ -223,8 +247,11 @@ async def process_message(message_data: Dict[str, Any]):
223
 
224
  logger.info(f"[DEBUG] Phương tiện: {keywords} - Hành vi: {hanh_vi_vi_pham} - Mục đích: {muc_dich}")
225
 
226
- # 2. Chuẩn bị thông tin message hiện tại
227
- current_message_info = {
 
 
 
228
  'message': message_text,
229
  'command': command,
230
  'content': remaining_text,
@@ -232,57 +259,16 @@ async def process_message(message_data: Dict[str, Any]):
232
  'vehicle': ','.join(keywords),
233
  'action': hanh_vi_vi_pham,
234
  'purpose': muc_dich,
235
- 'timestamp': timestamp
 
236
  }
237
 
238
- # 3. Xử lý theo trường hợp
239
- if open_conv:
240
- # Có conversation đang mở → Update
241
- logger.info(f"[UPDATE] Cập nhật conversation đang mở: {open_conv['conversation_id']}")
242
- log_kwargs = {
243
- 'conversation_id': open_conv['conversation_id'],
244
- 'user_id': sender_id,
245
- 'page_id': page_id,
246
- 'is_done': False,
247
- **current_message_info
248
- }
249
- # Merge thông tin: ưu tiên thông tin mới nếu có, giữ thông tin cũ nếu mới rỗng
250
- for key, value in open_conv.items():
251
- if key in log_kwargs and (not log_kwargs[key] or log_kwargs[key] in [None, '', [], {}]):
252
- log_kwargs[key] = value
253
-
254
- # Xử lý logic nghiệp vụ dựa trên thông tin tổng hợp
255
- response = await process_business_logic(log_kwargs, page_token)
256
-
257
- else:
258
- # Không có conversation đang mở → Tạo mới
259
- logger.info("[CREATE] Tạo conversation mới")
260
- log_kwargs = {
261
- 'conversation_id': None,
262
- 'user_id': sender_id,
263
- 'page_id': page_id,
264
- 'is_done': False,
265
- **current_message_info
266
- }
267
-
268
- # Lưu conversation mới trước
269
- await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**log_kwargs))
270
-
271
- # Lấy conversation_id vừa tạo
272
- updated_history = await loop.run_in_executor(
273
- executor, lambda: sheets_client.get_conversation_history(sender_id, page_id)
274
- )
275
- new_conv = next((row for row in updated_history if not row.get('isdone')), None)
276
- if new_conv:
277
- log_kwargs['conversation_id'] = new_conv['conversation_id']
278
- logger.info(f"[CREATE] Đã tạo conversation mới: {new_conv['conversation_id']}")
279
-
280
- # Xử lý logic nghiệp vụ dựa trên thông tin hiện tại
281
- response = await process_business_logic(log_kwargs, page_token)
282
 
283
- # 4. Gửi response và cập nhật final state
284
  await facebook_client.send_message(page_token, sender_id, response)
285
- await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**log_kwargs))
286
  return
287
 
288
  async def process_business_logic(log_kwargs: Dict[str, Any], page_token: str) -> str:
 
184
  logger.info("[DUPLICATE] Message duplicate, skipping log.")
185
  return
186
 
187
+ # 2. Ghi conversation mới NGAY LẬP TỨC với thông tin cơ bản
188
+ log_kwargs = {
189
+ 'conversation_id': None,
190
+ 'user_id': sender_id,
191
+ 'page_id': page_id,
192
+ 'message': message_text,
193
+ 'command': '',
194
+ 'content': '',
195
+ 'attachments': attachments,
196
+ 'vehicle': '',
197
+ 'action': '',
198
+ 'purpose': '',
199
+ 'timestamp': timestamp,
200
+ 'is_done': False
201
+ }
202
+ await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**log_kwargs))
203
+ logger.info("[CREATE] Đã ghi conversation mới vào sheet với thông tin cơ bản")
204
+
205
+ # 3. Lấy conversation_id vừa tạo
206
+ updated_history = await loop.run_in_executor(
207
+ executor, lambda: sheets_client.get_conversation_history(sender_id, page_id)
208
+ )
209
+ conv = next((row for row in updated_history if str(row['timestamp']) == str(timestamp) and str(row['recipient_id']) == str(sender_id) and str(row['page_id']) == str(page_id)), None)
210
+ if not conv:
211
+ logger.error("Không tìm thấy conversation vừa tạo!")
212
+ return
213
 
214
  # Get page access token (sync)
215
  page_token = supabase_client.get_page_token(page_id)
 
247
 
248
  logger.info(f"[DEBUG] Phương tiện: {keywords} - Hành vi: {hanh_vi_vi_pham} - Mục đích: {muc_dich}")
249
 
250
+ # 4. Update lại conversation với thông tin đầy đủ
251
+ update_kwargs = {
252
+ 'conversation_id': conv['conversation_id'],
253
+ 'user_id': sender_id,
254
+ 'page_id': page_id,
255
  'message': message_text,
256
  'command': command,
257
  'content': remaining_text,
 
259
  'vehicle': ','.join(keywords),
260
  'action': hanh_vi_vi_pham,
261
  'purpose': muc_dich,
262
+ 'timestamp': timestamp,
263
+ 'is_done': False
264
  }
265
 
266
+ # 5. Xử lý logic nghiệp vụ
267
+ response = await process_business_logic(update_kwargs, page_token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
+ # 6. Gửi response và cập nhật final state
270
  await facebook_client.send_message(page_token, sender_id, response)
271
+ await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**update_kwargs))
272
  return
273
 
274
  async def process_business_logic(log_kwargs: Dict[str, Any], page_token: str) -> str: