DreamStream-1 commited on
Commit
dd36977
·
verified ·
1 Parent(s): 055a7d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -19
app.py CHANGED
@@ -888,42 +888,74 @@ def split_message_for_whatsapp(message: str, max_length: int = 1000) -> list:
888
  return [message[i:i+max_length] for i in range(0, len(message), max_length)]
889
 
890
  def send_whatsjet_message(phone_number: str, message: str, media_type: str = None, media_path: str = None, filename: str = None) -> bool:
891
- """Send a message using WhatsJet API with optional media attachment (now supports header_image for images)"""
892
  if not all([WHATSJET_API_URL, WHATSJET_VENDOR_UID, WHATSJET_API_TOKEN]):
893
  logger.error("[WhatsJet] Missing environment variables.")
894
  return False
895
 
896
  url = f"{WHATSJET_API_URL}/{WHATSJET_VENDOR_UID}/contact/send-message?token={WHATSJET_API_TOKEN}"
897
 
898
- # Use WhatsJet's header_image for images with captions
899
- if media_type in ["image/jpeg", "image/png"] and media_path and (media_path.startswith("http://") or media_path.startswith("https://")):
900
- payload = {
901
- "phone_number": phone_number,
902
- "header_image": media_path,
903
- "message_body": message
904
- }
905
  try:
906
- response = httpx.post(
907
- url,
908
- json=payload,
909
- timeout=15
910
- )
911
- response.raise_for_status()
912
- logger.info(f"[WhatsJet] header_image message sent successfully to {phone_number}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
913
  return True
914
  except Exception as e:
915
- logger.error(f"[WhatsJet] Exception sending header_image message: {e}")
916
  return False
917
 
918
  # Handle other media messages (existing logic)
919
  if media_type and media_path:
920
  try:
921
- # For public URLs, download the content first
922
  if isinstance(media_path, str) and (media_path.startswith("http://") or media_path.startswith("https://")):
923
  response = requests.get(media_path, stream=True, timeout=15)
924
  response.raise_for_status()
925
  media_content = response.content
926
- logger.info(f"[WhatsJet][DEBUG] Downloaded image content-type: {response.headers.get('Content-Type')}")
927
  logger.info(f"[WhatsJet][DEBUG] First 20 bytes: {media_content[:20]}")
928
  else:
929
  with open(media_path, 'rb') as f:
@@ -934,7 +966,7 @@ def send_whatsjet_message(phone_number: str, message: str, media_type: str = Non
934
  "message_body": message,
935
  'media_type': media_type,
936
  'media_content': media_b64,
937
- 'media_filename': filename or os.path.basename(media_path) if not media_path.startswith('http') else filename or 'image.jpg'
938
  }
939
  try:
940
  response = httpx.post(
 
888
  return [message[i:i+max_length] for i in range(0, len(message), max_length)]
889
 
890
  def send_whatsjet_message(phone_number: str, message: str, media_type: str = None, media_path: str = None, filename: str = None) -> bool:
891
+ """Send a message using WhatsJet API with optional media attachment. For images, send the image as a media message (no caption), then send the caption as a separate text message."""
892
  if not all([WHATSJET_API_URL, WHATSJET_VENDOR_UID, WHATSJET_API_TOKEN]):
893
  logger.error("[WhatsJet] Missing environment variables.")
894
  return False
895
 
896
  url = f"{WHATSJET_API_URL}/{WHATSJET_VENDOR_UID}/contact/send-message?token={WHATSJET_API_TOKEN}"
897
 
898
+ # For images: send as media message (no caption), then send caption as text
899
+ if media_type in ["image/jpeg", "image/png"] and media_path:
 
 
 
 
 
900
  try:
901
+ # Download image if it's a URL
902
+ if media_path.startswith("http://") or media_path.startswith("https://"):
903
+ response = requests.get(media_path, stream=True, timeout=15)
904
+ response.raise_for_status()
905
+ media_content = response.content
906
+ logger.info(f"[WhatsJet][DEBUG] Downloaded image content-type: {response.headers.get('Content-Type')}")
907
+ logger.info(f"[WhatsJet][DEBUG] First 20 bytes: {media_content[:20]}")
908
+ else:
909
+ with open(media_path, 'rb') as f:
910
+ media_content = f.read()
911
+ media_b64 = base64.b64encode(media_content).decode('utf-8')
912
+ payload = {
913
+ "phone_number": phone_number,
914
+ "media_type": media_type,
915
+ "media_content": media_b64,
916
+ "media_filename": filename or os.path.basename(media_path) if not media_path.startswith('http') else filename or 'image.jpg',
917
+ "message_body": "" # No caption
918
+ }
919
+ # Send image (no caption)
920
+ try:
921
+ response = httpx.post(
922
+ url,
923
+ json=payload,
924
+ timeout=15
925
+ )
926
+ response.raise_for_status()
927
+ logger.info(f"[WhatsJet] Media image sent successfully to {phone_number}")
928
+ except Exception as e:
929
+ logger.error(f"[WhatsJet] Exception sending media image: {e}")
930
+ return False
931
+ # Send caption as a separate text message
932
+ if message.strip():
933
+ for chunk in split_message_for_whatsapp(message):
934
+ try:
935
+ text_payload = {"phone_number": phone_number, "message_body": chunk}
936
+ text_response = httpx.post(
937
+ url,
938
+ json=text_payload,
939
+ timeout=15
940
+ )
941
+ text_response.raise_for_status()
942
+ logger.info(f"[WhatsJet] Text chunk (caption) sent successfully to {phone_number}")
943
+ except Exception as e:
944
+ logger.error(f"[WhatsJet] Exception sending text chunk (caption): {e}")
945
+ return False
946
  return True
947
  except Exception as e:
948
+ logger.error(f"[WhatsJet] Exception preparing media image: {str(e)}")
949
  return False
950
 
951
  # Handle other media messages (existing logic)
952
  if media_type and media_path:
953
  try:
 
954
  if isinstance(media_path, str) and (media_path.startswith("http://") or media_path.startswith("https://")):
955
  response = requests.get(media_path, stream=True, timeout=15)
956
  response.raise_for_status()
957
  media_content = response.content
958
+ logger.info(f"[WhatsJet][DEBUG] Downloaded media content-type: {response.headers.get('Content-Type')}")
959
  logger.info(f"[WhatsJet][DEBUG] First 20 bytes: {media_content[:20]}")
960
  else:
961
  with open(media_path, 'rb') as f:
 
966
  "message_body": message,
967
  'media_type': media_type,
968
  'media_content': media_b64,
969
+ 'media_filename': filename or os.path.basename(media_path) if not media_path.startswith('http') else filename or 'file.bin'
970
  }
971
  try:
972
  response = httpx.post(