fix duplicate message
Browse files- app/main.py +73 -76
- app/sheets.py +2 -2
app/main.py
CHANGED
|
@@ -199,7 +199,7 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 199 |
logger.error(f"No access token found for page {page_id}")
|
| 200 |
return
|
| 201 |
|
| 202 |
-
# Extract command and keywords
|
| 203 |
command, remaining_text = extract_command(message_text)
|
| 204 |
# Sử dụng LLM để phân tích message_text và extract keywords, mục đích, hành vi vi phạm
|
| 205 |
llm_analysis = await llm_client.analyze(message_text)
|
|
@@ -223,12 +223,8 @@ 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 |
-
|
| 227 |
-
|
| 228 |
-
log_kwargs = {
|
| 229 |
-
'conversation_id': None,
|
| 230 |
-
'user_id': sender_id,
|
| 231 |
-
'page_id': page_id,
|
| 232 |
'message': message_text,
|
| 233 |
'command': command,
|
| 234 |
'content': remaining_text,
|
|
@@ -236,68 +232,78 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 236 |
'vehicle': ','.join(keywords),
|
| 237 |
'action': hanh_vi_vi_pham,
|
| 238 |
'purpose': muc_dich,
|
| 239 |
-
'timestamp': timestamp
|
| 240 |
-
'is_done': False
|
| 241 |
}
|
| 242 |
|
| 243 |
-
#
|
| 244 |
-
if not history:
|
| 245 |
-
log_kwargs['conversation_id'] = None
|
| 246 |
-
if not command:
|
| 247 |
-
if keywords:
|
| 248 |
-
# Có thông tin phương tiện
|
| 249 |
-
if hanh_vi_vi_pham:
|
| 250 |
-
embedding = await embedding_client.create_embedding(hanh_vi_vi_pham)
|
| 251 |
-
else:
|
| 252 |
-
embedding = await embedding_client.create_embedding(message_text)
|
| 253 |
-
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 254 |
-
matches = supabase_client.match_documents(embedding, vehicle_keywords=keywords)
|
| 255 |
-
logger.info(f"[DEBUG] matches: {matches}")
|
| 256 |
-
if matches:
|
| 257 |
-
response = await format_search_results(matches)
|
| 258 |
-
else:
|
| 259 |
-
response = "Xin lỗi, tôi không tìm thấy thông tin phù hợp."
|
| 260 |
-
log_kwargs['is_done'] = True
|
| 261 |
-
else:
|
| 262 |
-
# Không có thông tin phương tiện
|
| 263 |
-
response = "Vui lòng cho biết loại phương tiện bạn cần tìm (xe máy, ô tô...)"
|
| 264 |
-
log_kwargs['is_done'] = False
|
| 265 |
-
else:
|
| 266 |
-
# Có command
|
| 267 |
-
response = "Vui lòng cung cấp thêm thông tin và gõ lệnh \\xong khi hoàn tất."
|
| 268 |
-
log_kwargs['is_done'] = False
|
| 269 |
-
await facebook_client.send_message(page_token, sender_id, response)
|
| 270 |
-
await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**log_kwargs))
|
| 271 |
-
return
|
| 272 |
-
|
| 273 |
-
# 2. Nếu history có conversation (conversation cũ)
|
| 274 |
-
last_conv = history[-1] if history else None
|
| 275 |
-
last_command = last_conv['originalcommand'] if last_conv else ''
|
| 276 |
-
last_isdone = last_conv['isdone'] if last_conv else False
|
| 277 |
-
|
| 278 |
-
# --- Cập nhật log_kwargs theo lịch sử ---
|
| 279 |
-
log_kwargs_old = log_kwargs.copy()
|
| 280 |
-
log_kwargs_overwritten = {}
|
| 281 |
-
for key in log_kwargs.keys():
|
| 282 |
-
history_val = last_conv.get(key) if last_conv else None
|
| 283 |
-
current_val = log_kwargs[key]
|
| 284 |
-
if history_val not in [None, '', [], {}]:
|
| 285 |
-
if current_val not in [None, '', [], {}]:
|
| 286 |
-
log_kwargs_overwritten[key] = current_val # Lưu giá trị cũ để xử lý sau
|
| 287 |
-
log_kwargs[key] = history_val # Ưu tiên giá trị từ lịch sử
|
| 288 |
-
# --- END cập nhật log_kwargs ---
|
| 289 |
-
|
| 290 |
-
# Đảm bảo truyền đúng conversation_id khi update
|
| 291 |
if open_conv:
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
else:
|
| 294 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
if keywords:
|
| 299 |
# Có thông tin phương tiện
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
| 301 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 302 |
matches = supabase_client.match_documents(embedding, vehicle_keywords=keywords)
|
| 303 |
logger.info(f"[DEBUG] matches: {matches}")
|
|
@@ -306,35 +312,26 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 306 |
else:
|
| 307 |
response = "Xin lỗi, tôi không tìm thấy thông tin phù hợp."
|
| 308 |
log_kwargs['is_done'] = True
|
| 309 |
-
await facebook_client.send_message(page_token, sender_id, response)
|
| 310 |
-
await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**log_kwargs))
|
| 311 |
-
return
|
| 312 |
else:
|
| 313 |
# Không có thông tin phương tiện
|
| 314 |
response = "Vui lòng cho biết loại phương tiện bạn cần tìm (xe máy, ô tô...)"
|
| 315 |
-
|
| 316 |
-
await facebook_client.send_message(page_token, sender_id, response)
|
| 317 |
-
return
|
| 318 |
else:
|
| 319 |
-
#
|
| 320 |
if command == "xong":
|
| 321 |
# Tạo bài viết mới trên page (placeholder)
|
| 322 |
# TODO: Thay thế hàm này bằng logic thực tế
|
| 323 |
-
post_url = await create_facebook_post(page_token,
|
| 324 |
if post_url:
|
| 325 |
response = f"Bài viết đã được tạo thành công! Bạn có thể xem tại: {post_url}"
|
| 326 |
else:
|
| 327 |
response = "Đã xảy ra lỗi khi tạo bài viết. Vui lòng thử lại sau."
|
| 328 |
log_kwargs['is_done'] = True
|
| 329 |
-
await facebook_client.send_message(page_token, sender_id, response)
|
| 330 |
-
await loop.run_in_executor(executor, lambda: sheets_client.log_conversation(**log_kwargs))
|
| 331 |
-
return
|
| 332 |
else:
|
| 333 |
response = "Vui lòng cung cấp thêm thông tin và gõ lệnh \\xong khi hoàn tất."
|
| 334 |
log_kwargs['is_done'] = False
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
return
|
| 338 |
|
| 339 |
async def format_search_results(matches: List[Dict[str, Any]]) -> str:
|
| 340 |
if not matches:
|
|
|
|
| 199 |
logger.error(f"No access token found for page {page_id}")
|
| 200 |
return
|
| 201 |
|
| 202 |
+
# Extract command and keywords
|
| 203 |
command, remaining_text = extract_command(message_text)
|
| 204 |
# Sử dụng LLM để phân tích message_text và extract keywords, mục đích, hành vi vi phạm
|
| 205 |
llm_analysis = await llm_client.analyze(message_text)
|
|
|
|
| 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 |
'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:
|
| 289 |
+
"""
|
| 290 |
+
Xử lý logic nghiệp vụ dựa trên thông tin conversation.
|
| 291 |
+
"""
|
| 292 |
+
command = log_kwargs.get('command', '')
|
| 293 |
+
vehicle = log_kwargs.get('vehicle', '')
|
| 294 |
+
action = log_kwargs.get('action', '')
|
| 295 |
+
message = log_kwargs.get('message', '')
|
| 296 |
+
|
| 297 |
+
# Tách vehicle thành list keywords
|
| 298 |
+
keywords = [kw.strip() for kw in vehicle.split(',') if kw.strip()]
|
| 299 |
+
|
| 300 |
+
if not command:
|
| 301 |
if keywords:
|
| 302 |
# Có thông tin phương tiện
|
| 303 |
+
if action:
|
| 304 |
+
embedding = await embedding_client.create_embedding(action)
|
| 305 |
+
else:
|
| 306 |
+
embedding = await embedding_client.create_embedding(message)
|
| 307 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 308 |
matches = supabase_client.match_documents(embedding, vehicle_keywords=keywords)
|
| 309 |
logger.info(f"[DEBUG] matches: {matches}")
|
|
|
|
| 312 |
else:
|
| 313 |
response = "Xin lỗi, tôi không tìm thấy thông tin phù hợp."
|
| 314 |
log_kwargs['is_done'] = True
|
|
|
|
|
|
|
|
|
|
| 315 |
else:
|
| 316 |
# Không có thông tin phương tiện
|
| 317 |
response = "Vui lòng cho biết loại phương tiện bạn cần tìm (xe máy, ô tô...)"
|
| 318 |
+
log_kwargs['is_done'] = False
|
|
|
|
|
|
|
| 319 |
else:
|
| 320 |
+
# Có command
|
| 321 |
if command == "xong":
|
| 322 |
# Tạo bài viết mới trên page (placeholder)
|
| 323 |
# TODO: Thay thế hàm này bằng logic thực tế
|
| 324 |
+
post_url = await create_facebook_post(page_token, log_kwargs['user_id'], [log_kwargs])
|
| 325 |
if post_url:
|
| 326 |
response = f"Bài viết đã được tạo thành công! Bạn có thể xem tại: {post_url}"
|
| 327 |
else:
|
| 328 |
response = "Đã xảy ra lỗi khi tạo bài viết. Vui lòng thử lại sau."
|
| 329 |
log_kwargs['is_done'] = True
|
|
|
|
|
|
|
|
|
|
| 330 |
else:
|
| 331 |
response = "Vui lòng cung cấp thêm thông tin và gõ lệnh \\xong khi hoàn tất."
|
| 332 |
log_kwargs['is_done'] = False
|
| 333 |
+
|
| 334 |
+
return response
|
|
|
|
| 335 |
|
| 336 |
async def format_search_results(matches: List[Dict[str, Any]]) -> str:
|
| 337 |
if not matches:
|
app/sheets.py
CHANGED
|
@@ -191,8 +191,8 @@ class SheetsClient:
|
|
| 191 |
if row_index is not None:
|
| 192 |
# Lấy dữ liệu dòng hiện tại
|
| 193 |
current_row = values[row_index]
|
| 194 |
-
# Đảm bảo đủ
|
| 195 |
-
while len(current_row) <
|
| 196 |
current_row.append("")
|
| 197 |
# Tạo dòng mới với giá trị mới nếu có, giữ nguyên nếu không
|
| 198 |
new_row = [
|
|
|
|
| 191 |
if row_index is not None:
|
| 192 |
# Lấy dữ liệu dòng hiện tại
|
| 193 |
current_row = values[row_index]
|
| 194 |
+
# Đảm bảo đủ 13 cột (thêm processing)
|
| 195 |
+
while len(current_row) < 13:
|
| 196 |
current_row.append("")
|
| 197 |
# Tạo dòng mới với giá trị mới nếu có, giữ nguyên nếu không
|
| 198 |
new_row = [
|