VietCat commited on
Commit
135c478
·
1 Parent(s): 7fffc3e

fix duplicate message

Browse files
Files changed (2) hide show
  1. app/main.py +25 -25
  2. app/sheets.py +35 -35
app/main.py CHANGED
@@ -176,15 +176,15 @@ async def process_message(message_data: Dict[str, Any]):
176
 
177
  log_kwargs = {
178
  'conversation_id': None,
179
- 'user_id': sender_id,
180
  'page_id': page_id,
181
  'originaltext': message_text,
182
- 'command': '',
183
- 'content': '',
184
- 'attachments': attachments,
185
- 'vehicle': '',
186
- 'action': '',
187
- 'purpose': '',
188
  'timestamp': [timestamp],
189
  'isdone': False
190
  }
@@ -207,15 +207,15 @@ async def process_message(message_data: Dict[str, Any]):
207
  return
208
  conv = {
209
  'conversation_id': row.get('conversation_id'),
210
- 'user_id': row.get('recipient_id'),
211
  'page_id': row.get('page_id'),
212
  'originaltext': row.get('originaltext'),
213
- 'command': row.get('originalcommand'),
214
- 'content': row.get('originalcontent'),
215
- 'attachments': row.get('originalattachments'),
216
- 'vehicle': row.get('originalvehicle'),
217
- 'action': row.get('originalaction'),
218
- 'purpose': row.get('originalpurpose'),
219
  'timestamp': row_timestamps,
220
  'isdone': row.get('isdone')
221
  }
@@ -277,15 +277,15 @@ async def process_message(message_data: Dict[str, Any]):
277
  # 4. Update lại conversation với thông tin đầy đủ
278
  update_kwargs = {
279
  'conversation_id': conv['conversation_id'],
280
- 'user_id': sender_id,
281
  'page_id': page_id,
282
  'originaltext': message_text,
283
- 'command': command,
284
- 'content': remaining_text,
285
- 'attachments': attachments,
286
- 'vehicle': ','.join(keywords),
287
- 'action': hanh_vi_vi_pham,
288
- 'purpose': muc_dich,
289
  'timestamp': conv['timestamp'],
290
  'isdone': False
291
  }
@@ -306,9 +306,9 @@ async def process_business_logic(log_kwargs: Dict[str, Any], page_token: str) ->
306
  """
307
  Xử lý logic nghiệp vụ dựa trên thông tin conversation.
308
  """
309
- command = log_kwargs.get('command', '')
310
- vehicle = log_kwargs.get('vehicle', '')
311
- action = log_kwargs.get('action', '')
312
  message = log_kwargs.get('originaltext', '')
313
 
314
  # Tách vehicle thành list keywords
@@ -340,7 +340,7 @@ async def process_business_logic(log_kwargs: Dict[str, Any], page_token: str) ->
340
  if command == "xong":
341
  # Tạo bài viết mới trên page (placeholder)
342
  # TODO: Thay thế hàm này bằng logic thực tế
343
- post_url = await create_facebook_post(page_token, log_kwargs['user_id'], [log_kwargs])
344
  if post_url:
345
  response = f"Bài viết đã được tạo thành công! Bạn có thể xem tại: {post_url}"
346
  else:
 
176
 
177
  log_kwargs = {
178
  'conversation_id': None,
179
+ 'recipient_id': sender_id,
180
  'page_id': page_id,
181
  'originaltext': message_text,
182
+ 'originalcommand': '',
183
+ 'originalcontent': '',
184
+ 'originalattachments': attachments,
185
+ 'originalvehicle': '',
186
+ 'originalaction': '',
187
+ 'originalpurpose': '',
188
  'timestamp': [timestamp],
189
  'isdone': False
190
  }
 
207
  return
208
  conv = {
209
  'conversation_id': row.get('conversation_id'),
210
+ 'recipient_id': row.get('recipient_id'),
211
  'page_id': row.get('page_id'),
212
  'originaltext': row.get('originaltext'),
213
+ 'originalcommand': row.get('originalcommand'),
214
+ 'originalcontent': row.get('originalcontent'),
215
+ 'originalattachments': row.get('originalattachments'),
216
+ 'originalvehicle': row.get('originalvehicle'),
217
+ 'originalaction': row.get('originalaction'),
218
+ 'originalpurpose': row.get('originalpurpose'),
219
  'timestamp': row_timestamps,
220
  'isdone': row.get('isdone')
221
  }
 
277
  # 4. Update lại conversation với thông tin đầy đủ
278
  update_kwargs = {
279
  'conversation_id': conv['conversation_id'],
280
+ 'recipient_id': sender_id,
281
  'page_id': page_id,
282
  'originaltext': message_text,
283
+ 'originalcommand': command,
284
+ 'originalcontent': remaining_text,
285
+ 'originalattachments': attachments,
286
+ 'originalvehicle': ','.join(keywords),
287
+ 'originalaction': hanh_vi_vi_pham,
288
+ 'originalpurpose': muc_dich,
289
  'timestamp': conv['timestamp'],
290
  'isdone': False
291
  }
 
306
  """
307
  Xử lý logic nghiệp vụ dựa trên thông tin conversation.
308
  """
309
+ command = log_kwargs.get('originalcommand', '')
310
+ vehicle = log_kwargs.get('originalvehicle', '')
311
+ action = log_kwargs.get('originalaction', '')
312
  message = log_kwargs.get('originaltext', '')
313
 
314
  # Tách vehicle thành list keywords
 
340
  if command == "xong":
341
  # Tạo bài viết mới trên page (placeholder)
342
  # TODO: Thay thế hàm này bằng logic thực tế
343
+ post_url = await create_facebook_post(page_token, log_kwargs['recipient_id'], [log_kwargs])
344
  if post_url:
345
  response = f"Bài viết đã được tạo thành công! Bạn có thể xem tại: {post_url}"
346
  else:
app/sheets.py CHANGED
@@ -119,21 +119,21 @@ class SheetsClient:
119
  def log_conversation(
120
  self,
121
  conversation_id: str,
122
- user_id: str,
123
  page_id: str,
124
  originaltext: str = "",
125
- command: str = "",
126
- content: str = "",
127
- attachments: Optional[List[str]] = None,
128
- vehicle: str = "",
129
- action: str = "",
130
- purpose: str = "",
131
  timestamp: str = "",
132
  isdone: bool = False
133
  ) -> Optional[Dict[str, Any]]:
134
  """
135
  Ghi log hội thoại vào Google Sheets.
136
- Dùng originaltext cho cột message trong sheet và các logic liên quan.
137
  """
138
  try:
139
  if not self.service:
@@ -157,11 +157,11 @@ class SheetsClient:
157
  row_timestamps = json.loads(row[10]) if row[10] else []
158
  if isinstance(row_timestamps, list) and len(row_timestamps) == 1 and isinstance(row_timestamps[0], list):
159
  row_timestamps = row_timestamps[0]
160
- row_user_id = row[4]
161
  row_page_id = row[5]
162
- if (str(timestamp) in [str(ts) for ts in row_timestamps] and str(row_user_id) == str(user_id) and str(row_page_id) == str(page_id)):
163
  # Found duplicate, return existing conversation
164
- logger.info(f"Found duplicate conversation for user {user_id}, page {page_id}, timestamp {timestamp}")
165
  return {
166
  'conversation_id': row[0],
167
  'originalcommand': row[1],
@@ -178,18 +178,18 @@ class SheetsClient:
178
  }
179
 
180
  # No duplicate found, create new conversation
181
- conversation_id = generate_conversation_id(user_id, page_id, ts)
182
  new_row = [
183
  conversation_id,
184
- command,
185
- content,
186
- json.dumps(attachments or []),
187
- user_id,
188
  page_id,
189
  originaltext,
190
- vehicle,
191
- action,
192
- purpose,
193
  json.dumps(timestamp),
194
  str(isdone).lower()
195
  ]
@@ -206,20 +206,20 @@ class SheetsClient:
206
  body=body
207
  ).execute()
208
 
209
- logger.info(f"Thêm mới conversation: {conversation_id} | Giá trị: {dict(zip(['conversation_id','command','content','attachments','user_id','page_id','originaltext','vehicle','action','purpose','timestamp','isdone'], new_row))}")
210
 
211
  # Return the conversation data directly
212
  return {
213
  'conversation_id': conversation_id,
214
- 'originalcommand': command,
215
- 'originalcontent': content,
216
- 'originalattachments': attachments or [],
217
- 'recipient_id': user_id,
218
  'page_id': page_id,
219
  'originaltext': originaltext,
220
- 'originalvehicle': vehicle,
221
- 'originalaction': action,
222
- 'originalpurpose': purpose,
223
  'timestamp': timestamp,
224
  'isdone': isdone
225
  }
@@ -248,15 +248,15 @@ class SheetsClient:
248
  current_timestamps.append(timestamp)
249
  new_row = [
250
  conversation_id,
251
- command if command else current_row[1],
252
- content if content else current_row[2],
253
- json.dumps(attachments) if attachments is not None else current_row[3],
254
- user_id if user_id else current_row[4],
255
  page_id if page_id else current_row[5],
256
  originaltext if originaltext else current_row[6],
257
- vehicle if vehicle else current_row[7],
258
- action if action else current_row[8],
259
- purpose if purpose else current_row[9],
260
  json.dumps(current_timestamps),
261
  str(isdone).lower() if isdone is not None else current_row[11]
262
  ]
@@ -271,7 +271,7 @@ class SheetsClient:
271
  valueInputOption='RAW',
272
  body=body
273
  ).execute()
274
- changed_cols = ['conversation_id','command','content','attachments','user_id','page_id','originaltext','vehicle','action','purpose','timestamp','isdone']
275
  for idx, (old, new) in enumerate(zip(current_row, new_row)):
276
  if old != new:
277
  changed_cols.append(changed_cols[idx])
 
119
  def log_conversation(
120
  self,
121
  conversation_id: str,
122
+ recipient_id: str,
123
  page_id: str,
124
  originaltext: str = "",
125
+ originalcommand: str = "",
126
+ originalcontent: str = "",
127
+ originalattachments: Optional[List[str]] = None,
128
+ originalvehicle: str = "",
129
+ originalaction: str = "",
130
+ originalpurpose: str = "",
131
  timestamp: str = "",
132
  isdone: bool = False
133
  ) -> Optional[Dict[str, Any]]:
134
  """
135
  Ghi log hội thoại vào Google Sheets.
136
+ Dùng các trường original* cho các cột tương ứng trong sheet và các logic liên quan.
137
  """
138
  try:
139
  if not self.service:
 
157
  row_timestamps = json.loads(row[10]) if row[10] else []
158
  if isinstance(row_timestamps, list) and len(row_timestamps) == 1 and isinstance(row_timestamps[0], list):
159
  row_timestamps = row_timestamps[0]
160
+ row_recipient_id = row[4]
161
  row_page_id = row[5]
162
+ if (str(timestamp) in [str(ts) for ts in row_timestamps] and str(row_recipient_id) == str(recipient_id) and str(row_page_id) == str(page_id)):
163
  # Found duplicate, return existing conversation
164
+ logger.info(f"Found duplicate conversation for user {recipient_id}, page {page_id}, timestamp {timestamp}")
165
  return {
166
  'conversation_id': row[0],
167
  'originalcommand': row[1],
 
178
  }
179
 
180
  # No duplicate found, create new conversation
181
+ conversation_id = generate_conversation_id(recipient_id, page_id, ts)
182
  new_row = [
183
  conversation_id,
184
+ originalcommand,
185
+ originalcontent,
186
+ json.dumps(originalattachments or []),
187
+ recipient_id,
188
  page_id,
189
  originaltext,
190
+ originalvehicle,
191
+ originalaction,
192
+ originalpurpose,
193
  json.dumps(timestamp),
194
  str(isdone).lower()
195
  ]
 
206
  body=body
207
  ).execute()
208
 
209
+ logger.info(f"Thêm mới conversation: {conversation_id} | Giá trị: {dict(zip(['conversation_id','originalcommand','originalcontent','originalattachments','recipient_id','page_id','originaltext','originalvehicle','originalaction','originalpurpose','timestamp','isdone'], new_row))}")
210
 
211
  # Return the conversation data directly
212
  return {
213
  'conversation_id': conversation_id,
214
+ 'originalcommand': originalcommand,
215
+ 'originalcontent': originalcontent,
216
+ 'originalattachments': originalattachments or [],
217
+ 'recipient_id': recipient_id,
218
  'page_id': page_id,
219
  'originaltext': originaltext,
220
+ 'originalvehicle': originalvehicle,
221
+ 'originalaction': originalaction,
222
+ 'originalpurpose': originalpurpose,
223
  'timestamp': timestamp,
224
  'isdone': isdone
225
  }
 
248
  current_timestamps.append(timestamp)
249
  new_row = [
250
  conversation_id,
251
+ originalcommand if originalcommand else current_row[1],
252
+ originalcontent if originalcontent else current_row[2],
253
+ json.dumps(originalattachments) if originalattachments is not None else current_row[3],
254
+ recipient_id if recipient_id else current_row[4],
255
  page_id if page_id else current_row[5],
256
  originaltext if originaltext else current_row[6],
257
+ originalvehicle if originalvehicle else current_row[7],
258
+ originalaction if originalaction else current_row[8],
259
+ originalpurpose if originalpurpose else current_row[9],
260
  json.dumps(current_timestamps),
261
  str(isdone).lower() if isdone is not None else current_row[11]
262
  ]
 
271
  valueInputOption='RAW',
272
  body=body
273
  ).execute()
274
+ changed_cols = ['conversation_id','originalcommand','originalcontent','originalattachments','recipient_id','page_id','originaltext','originalvehicle','originalaction','originalpurpose','timestamp','isdone']
275
  for idx, (old, new) in enumerate(zip(current_row, new_row)):
276
  if old != new:
277
  changed_cols.append(changed_cols[idx])