rairo commited on
Commit
ae96e41
·
verified ·
1 Parent(s): f835629

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +81 -13
main.py CHANGED
@@ -111,6 +111,42 @@ def create_reply_button_message(text: str, buttons: List[Dict]) -> Dict:
111
  }
112
 
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  @app.get("/")
115
  def verify_token():
116
  """Webhook verification endpoint"""
@@ -282,52 +318,84 @@ def hook():
282
  return "Internal server error", 500
283
 
284
  def handle_interactive_message(messenger, data, mobile, carts):
285
- """Handle interactive message responses"""
286
  try:
287
  response = messenger.get_interactive_response(data)
288
  button_id = response.get("id")
289
 
290
  if button_id == "add_to_cart":
291
- # Add products to cart
292
  if mobile not in carts:
293
  carts[mobile] = []
294
- # Add current products to cart logic here
295
 
296
  buttons = [
297
- {"id": "more_shopping", "title": "Do More Shopping"},
298
  {"id": "checkout", "title": "Checkout"}
299
  ]
300
- button_message = create_reply_button_message("Products added to cart!", buttons)
 
 
 
301
  messenger.send_reply_button(
302
  recipient_id=mobile,
303
  button=button_message
304
  )
305
 
 
 
 
 
 
 
 
306
  elif button_id == "checkout":
307
  if mobile not in carts or not carts[mobile]:
308
  messenger.send_message("Your cart is empty!", mobile)
309
  return
310
 
 
 
 
 
 
 
 
 
 
 
 
311
  buttons = [
312
- {"id": "confirm_checkout", "title": "Confirm"},
313
- {"id": "cancel_checkout", "title": "Cancel"}
314
  ]
315
- button_message = create_reply_button_message("Ready to complete your purchase?", buttons)
316
  messenger.send_reply_button(
317
  recipient_id=mobile,
318
  button=button_message
319
  )
320
 
321
- elif button_id == "confirm_checkout":
322
- # Process checkout
323
- carts[mobile] = [] # Clear cart
324
- messenger.send_message("Thank you for your purchase!", mobile)
 
 
 
 
 
 
 
 
 
 
 
325
 
326
  except Exception as e:
327
  logger.error(f"Error handling interactive message: {str(e)}")
328
  messenger.send_message("Sorry, something went wrong.", mobile)
329
 
330
- # Keep your original media handling, DNS setup, and other utility functions
331
 
332
  def test_connection():
333
  """Test DNS resolution and connection to Graph API"""
 
111
  }
112
 
113
 
114
+ def handle_media_message(messenger, data, message_type, mobile):
115
+ """
116
+ Handle media messages (images, documents, audio)
117
+ Retrieve and process media content
118
+ """
119
+ try:
120
+ # Download media content based on type
121
+ if message_type == "image":
122
+ media_url = messenger.get_image_url(data)
123
+ elif message_type == "document":
124
+ media_url = messenger.get_document_url(data)
125
+ elif message_type == "audio":
126
+ media_url = messenger.get_audio_url(data)
127
+ else:
128
+ logger.error(f"Unsupported media type: {message_type}")
129
+ return None
130
+
131
+ # Download media content
132
+ response = requests.get(media_url, headers={
133
+ "Authorization": f"Bearer {os.getenv('whatsapp_token')}"
134
+ })
135
+
136
+ if response.status_code != 200:
137
+ logger.error(f"Failed to download media: {response.status_code}")
138
+ messenger.send_message("Sorry, I couldn't process your media.", mobile)
139
+ return None
140
+
141
+ # Return media content for further processing
142
+ return response.content
143
+
144
+ except Exception as e:
145
+ logger.error(f"Error handling media message: {str(e)}")
146
+ messenger.send_message("Sorry, I couldn't process your media.", mobile)
147
+ return None
148
+
149
+
150
  @app.get("/")
151
  def verify_token():
152
  """Webhook verification endpoint"""
 
318
  return "Internal server error", 500
319
 
320
  def handle_interactive_message(messenger, data, mobile, carts):
321
+ """Handle interactive message responses with enhanced cart functionality"""
322
  try:
323
  response = messenger.get_interactive_response(data)
324
  button_id = response.get("id")
325
 
326
  if button_id == "add_to_cart":
327
+ # Add products to cart (assuming cart data is stored in the previous interaction)
328
  if mobile not in carts:
329
  carts[mobile] = []
330
+ # Placeholder for adding last analyzed products to cart
331
 
332
  buttons = [
333
+ {"id": "continue_shopping", "title": "Continue Shopping"},
334
  {"id": "checkout", "title": "Checkout"}
335
  ]
336
+ button_message = create_reply_button_message(
337
+ "Products added to cart! What would you like to do next?",
338
+ buttons
339
+ )
340
  messenger.send_reply_button(
341
  recipient_id=mobile,
342
  button=button_message
343
  )
344
 
345
+ elif button_id == "continue_shopping":
346
+ # Encourage further shopping
347
+ messenger.send_message(
348
+ "Great! You can continue shopping by sending me a text or image of what you're looking for.",
349
+ mobile
350
+ )
351
+
352
  elif button_id == "checkout":
353
  if mobile not in carts or not carts[mobile]:
354
  messenger.send_message("Your cart is empty!", mobile)
355
  return
356
 
357
+ # Calculate total
358
+ total = sum(product['price'] for product in carts[mobile])
359
+
360
+ # Generate receipt
361
+ receipt_text = "Your Purchase Receipt:\n\n"
362
+ for product in carts[mobile]:
363
+ receipt_text += f"- {product['product']}: ${product['price']:.2f}\n"
364
+ receipt_text += f"\nTotal: ${total:.2f}\n\n"
365
+ receipt_text += "Expected Delivery: Within 1 hour\n"
366
+ receipt_text += "Thank you for your purchase!"
367
+
368
  buttons = [
369
+ {"id": "confirm_order", "title": "Confirm Order"},
370
+ {"id": "modify_order", "title": "Modify Order"}
371
  ]
372
+ button_message = create_reply_button_message(receipt_text, buttons)
373
  messenger.send_reply_button(
374
  recipient_id=mobile,
375
  button=button_message
376
  )
377
 
378
+ elif button_id == "confirm_order":
379
+ # Finalize order
380
+ messenger.send_message(
381
+ "Order confirmed! Your items will be delivered within 1 hour. Thank you!",
382
+ mobile
383
+ )
384
+ # Clear the cart
385
+ carts[mobile] = []
386
+
387
+ elif button_id == "modify_order":
388
+ # Allow user to modify order
389
+ messenger.send_message(
390
+ "Please tell us any changes you'd like to make to your order.",
391
+ mobile
392
+ )
393
 
394
  except Exception as e:
395
  logger.error(f"Error handling interactive message: {str(e)}")
396
  messenger.send_message("Sorry, something went wrong.", mobile)
397
 
398
+
399
 
400
  def test_connection():
401
  """Test DNS resolution and connection to Graph API"""